ภาพรวม
ตัวอย่างนี้สาธิตการจัดการ Push Notification จาก Firebase Cloud Messaging (FCM) และเปิด Activity ที่ต้องการเมื่อผู้ใช้กดที่การแจ้งเตือน
ขั้นตอนที่ 1: เพิ่ม Dependency Firebase
// build.gradle (app level)
dependencies {
implementation 'com.google.firebase:firebase-messaging:23.0.0'
// หรือเวอร์ชันล่าสุด
}
ขั้นตอนที่ 2: สร้าง MyFirebaseMessagingService
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String default_notification_channel_id = "default";
@Override
public void onNewToken(String token) {
super.onNewToken(token);
// ส่ง token ไปยังเซิร์ฟเวอร์ของคุณ
Log.d("FCM_TOKEN", "Refreshed token: " + token);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// สร้าง Intent เพื่อเปิด MainActivity
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
notificationIntent.putExtra("NotificationMessage", "I am from Notification");
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent resultIntent = PendingIntent.getActivity(
getApplicationContext(), 0, notificationIntent,
PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
);
// สร้าง Notification
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
getApplicationContext(), default_notification_channel_id)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Test")
.setContentText("Hello! This is my first push notification")
.setContentIntent(resultIntent)
.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
// สร้าง Channel สำหรับ Android O+
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
}
}
ขั้นตอนที่ 3: ลงทะเบียน Service ใน AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.tutorialspoint.com.notifyme">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Firebase Messaging Service -->
<service
android:name=".MyFirebaseMessagingService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
ขั้นตอนที่ 4: รับข้อมูลใน MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// รับข้อมูลจาก Notification
handleNotificationIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleNotificationIntent(intent);
}
private void handleNotificationIntent(Intent intent) {
if (intent != null && intent.getExtras() != null) {
String message = intent.getStringExtra("NotificationMessage");
if (message != null) {
// แสดงข้อความหรือนำทางไปหน้าที่ต้องการ
TextView textView = findViewById(R.id.textView);
if (textView != null) textView.setText(message);
}
}
}
ประเภทของ Push Notification
1. Notification Message (Display Message)
FCM แสดงการแจ้งเตือนอัตโนมัติเมื่อแอปอยู่ในพื้นหลัง onMessageReceived ไม่ถูกเรียก
2. Data Message
ส่งข้อมูล JSON ไปยัง onMessageReceived() ทำงานได้ทั้ง Foreground และ Background
3. Both (Notification + Data)
มีทั้งการแจ้งเตือนและข้อมูล Background: แสดงแจ้งเตือน + ข้อมูลใน Intent Foreground: onMessageReceived() ได้รับข้อมูลทั้งหมด
แนวทางปฏิบัติที่ดีที่สุด
- ใช้
PendingIntent.FLAG_IMMUTABLEสำหรับ Android 12+ - ตั้งค่า
FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOPป้องกัน Activity ซ้ำ - จัดการ Deep Link เพื่อนำทางไปหน้าเฉพาะตามประเภท Notification
- ทดสอบทั้ง Foreground และ Background state