Firebase cloud messaging - Step by step procedure

Implement FCM cloud messaging in Android app through Android studio is now simple. The step by step procedure is,

1. Create a new project in android studio

2. Click on tab Tools -> Firebase

3. Firebase assistant wiil open on right hand side of studio

4. A new dialog box appears to connect to firebase (This step creates a new project in the same name, here FCMMessaging in firebase console)

5. Then add FCM to app, through firebase assisstant, this step will add dependencies that is required for the app.

6. Now Create a service which should extend FirebaseInstanceIdService, which should override the method onTokenRefresh(), code snippet is as follows

 @Override
 public void onTokenRefresh() {
   super.onTokenRefresh();

   // Get updated InstanceID token.
   String refreshedToken = FirebaseInstanceId.getInstance().getToken();
   Log.e("FirebaseInstanceID", "Refresh token: " + refreshedToken);
}



7. Now create another service which should extend FirebaseMessagingService and overrides the method, onMessageReceived(). Here in this service, we will receive the remote message pushed by firebase. After receiving the remote message, we can do anything, here I am just displaying it as a notification. The code snippet is as follows,

  @Override
  public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    String image = remoteMessage.getNotification().getIcon();
    String title = remoteMessage.getNotification().getTitle();
    String text = remoteMessage.getNotification().getBody();
    String sound = remoteMessage.getNotification().getSound();
    
    Object obj = remoteMessage.getData().get("id");
    if (obj != null) {
      id = Integer.valueOf(obj.toString());
    }

    this.sendNotification(new NotificationMetaData(image, id, title, text, sound));
  }

  private void sendNotification(NotificationMetaData notificationData) {
        Intent intent = new Intent(this, LauncherActivity.class);
        intent.putExtra(NotificationMetaData.TEXT, notificationData.getTextMessage());

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder notificationBuilder = null;
        try {

            notificationBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(URLDecoder.decode(notificationData.getTitle(), "UTF-8"))
                    .setContentText(URLDecoder.decode(notificationData.getTextMessage(), "UTF-8"))
                    .setAutoCancel(true)
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                    .setContentIntent(pendingIntent);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (notificationBuilder != null) {
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(notificationData.getId(), notificationBuilder.build());
        } else {
            Log.e("FCMMessagingService", "Notification builder is null");
        }
    }


8. And the last step is go to firebase console, click on Notifications tab of left hand side. Create a new message, select relevant options, if sending to single device, specify the registration id which we will get from the MyFirebaseInsatanceIdService. Just log it, and get it from logcat. That is it, type title and text you need to specify for the remote message and click on Send Message. You are done. You will receive the remoteMessage in your device. It is as simple as that.

You can get the complete source code here, GitHub Repo

Happy Coding

Comments

Popular posts from this blog

Open Gallery and get the selected image in appplication

AlarmManager and Notification in Android

Dismiss or Cancel dialog by swipe gesture