Giới thiệu
Ví dụ này minh họa cách xử lý Push Notification (FCM - Firebase Cloud Messaging) để mở một Activity cụ thể khi người dùng nhấn vào thông báo. Sử dụng FirebaseMessagingService để nhận tin nhắn từ server.
Yêu cầu trước
- Đã thiết lập Firebase project và thêm
google-services.jsonvào app - Thêm dependency:
implementation 'com.google.firebase:firebase-messaging:23.0.0'(phiên bản mới nhất)
Code xử lý (src/MyFirebaseMessagingService.java)
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);
// Gửi token lên server của bạn để gửi push sau này
Log.d("FCM_TOKEN", "Token mới: " + token);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// Tạo Intent mở MainActivity khi nhấn thông báo
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
notificationIntent.putExtra("NotificationMessage", "Tôi đến từ Push 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);
// Xây dựng thông báo
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
getApplicationContext(), default_notification_channel_id)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Test Push Notification")
.setContentText("Xin chào! Đây là push notification đầu tiên của tôi")
.setContentIntent(resultIntent)
.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Tạo Notification Channel cho 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());
}
}
Đăng ký Service trong AndroidManifest.xml
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Xử lý dữ liệu trong MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Xử lý dữ liệu từ Push Notification
handleNotificationIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleNotificationIntent(intent);
}
private void handleNotificationIntent(Intent intent) {
if (intent != null && intent.hasExtra("NotificationMessage")) {
String message = intent.getStringExtra("NotificationMessage");
// Cập nhật UI, hiển thị message, điều hướng màn hình, v.v.
Log.d("PUSH_DATA", "Nhận được: " + message);
}
}
Luồng hoạt động
- Server gửi tin nhắn FCM đến thiết bị
MyFirebaseMessagingService.onMessageReceived()được gọi- Tạo Notification với
PendingIntenttrỏ đếnMainActivity - User nhấn thông báo → Mở
MainActivityvới extra data MainActivity.onNewIntent()xử lý dữ liệu
Lưu ý quan trọng
- Trên Android 12+ (API 31+),
PendingIntentbắt buộc có flagFLAG_IMMUTABLEhoặcFLAG_MUTABLE - Nếu app bị kill,
onMessageReceivedvẫn chạy do FCM wake up app - Data payload vs Notification payload: Ưu tiên dùng Data payload để tự kiểm soát hiển thị