Thông Báo (Notification) Trong Android Với Firebase Cloud Messaging

Xử lý nhận thông báo và hiển thị thông báo nổi trên màn hình:

Bạn cần tạo một service có tên là MyFirebaseService và extends từ FirebaseMessagingService như sau:

public class MyFirebaseService extends FirebaseMessagingService { private static final String TAG = "MyFirebaseService"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { // handle a notification payload. if (remoteMessage.getNotification() != null) { Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); sendNotification(remoteMessage.getNotification().getBody()); } } @Override public void onNewToken(String token) { Log.d(TAG, "Refreshed token: " + token); sendRegistrationToServer(token); } private void sendRegistrationToServer(String token) { // TODO: Implement this method to send token to your app server. } private void sendNotification(String messageBody) { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); String channelId = getString(R.string.project_id); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId) .setSmallIcon(R.drawable.ic_launcher_background) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background)) .setContentTitle(getString(R.string.project_id)) .setContentText(messageBody) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent) .setDefaults(Notification.DEFAULT_ALL) .setPriority(NotificationManager.IMPORTANCE_HIGH) .addAction(new NotificationCompat.Action( android.R.drawable.sym_call_missed, "Cancel", PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT))) .addAction(new NotificationCompat.Action( android.R.drawable.sym_call_outgoing, "OK", PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT))); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Since android Oreo notification channel is needed. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel( channelId, "Channel human readable title", NotificationManager.IMPORTANCE_DEFAULT); notificationManager.createNotificationChannel(channel); } notificationManager.notify(0, notificationBuilder.build()); } }

Mình sẽ giải thích sơ qua về các method ở trên nhé:

  • onMessageReceived(): Phương thức này sẽ chạy khi có thông báo từ firebase gửi về. Cần lưu ý rằng đối với loại thông báo Notification messages thì phương thức này chỉ chạy khi ứng dụng của bạn đang ở trạng thái Foreground, còn nếu ứng dụng đang ở trạng thái Background thì thông báo sẽ được hiển thị trong khay thông báo của thiết bị và phương thức này sẽ không được chạy (Như bảng mình đã trình bày ở phần trên). Đây cũng chính là nguyên nhân mình tạo Service xử lý hiển thị thông báo để cho các bạn thấy rõ việc xử lý nhận thông báo của ứng dụng đối với loại thông báo là Notification messages.
  • onNewToken(): Khi một thiết bị cài đặt ứng dụng thì nó sẽ đăng ký một device_token lên cho Firebase để Firebase có thể dựa vào các token này để gửi các thông báo về thiết bị. Với phương thức này bạn có thể lấy được token đó. Bạn có thể lưu token này vào Database để phục vụ cho các chức năng chẳng hạn như gửi thông báo, tin nhắn từ một website về các thiết bị,...
  • sendNotification(): Đây là phương thức hiển thị thông báo đã nhận được dưới dạng một popup nổi trên màn hình thiết bị, mình đã thiết lập có thêm 2 button là OKCancel để phân biệt với thông báo được xử lý hiển thị trên khay hệ thống khi ứng dụng ở trạng thái Foreground.

Tiếp theo bạn cần đăng ký Service này bằng cách copy và dán đoạn code sau vào file AndroidManifest.xml:

<service android:name=".Services.MyFirebaseService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>

Bạn tiến hành build ứng dụng ra máy ảo (hoặc máy thật) (máy mình hơi yếu nên mình build ứng dụng ra máy thật luôn, hehe 😄). Okie, vậy là đã xong 1 ứng dụng nho nhỏ nhận thông báo. Việc tiếp theo là chúng ta cần gửi thông báo để test thôi 😄

Từ khóa » Xin Noti Là Gì