Android - Setup Firebase Cloud Messaging Notification & Get Registration Token

Firebase has become a popular service for sending notifications to users' device. If you haven't already known what is Firebase, it's a Backend-as-a-Service — BaaS application development platform. From all of services provided by Firebase, the Cloud Messaging is commonly used for sending notifications. It allows us to send notifications to clients which can be an Android app, iOS app, web application and so on. This tutorial shows you how to integrate your Android application with Firebase Cloud Messaging, so that your app users can receive notifications.

How Firebase Notification Works?

With Firebase, it's possible to send notifications to multiple devices. In order to send a notification to a particular device, you need to get the registration token of the device. Firebase saves all the tokens and by giving a valid token, it knows where the notification should be sent.

I'm going to show yo the process of how to get the token from registering Firebase account until integrating Firebase service with the Android application.

Register for a Firebase Account

To register, open the Firebase console.

https://console.firebase.google.com/

Firebase Console - Create Project

You'll be asked to enter your project name and accept all terms. Once you've successfully created your project, you will see the project overview page on which you can select which platform your application is.

Choose Android and you'll be redirected to a page where you need to fill the Android package name of your app. Optionally you can also input nickname of the app and debug signing certificate SHA-1.

Firebase Register Android app

After that, you need to download the generated google-services.json file which will be used for authentication.

Firebase Download Android App Config

Set Up Android Application

Inside dependencies block of the app level build.gradle file, add the following dependencies:

  • implementation 'com.google.firebase:firebase-core:16.0.1'
  • compile 'com.google.firebase:firebase-messaging:17.0.0'

On the outermost of the same file, also add apply plugin: 'com.google.gms.google-services' In the end, your file should look like this

app/build.gradle

  apply plugin: 'com.android.application'

  android {
    ...
  }

  dependencies {
    ...
    implementation 'com.google.firebase:firebase-core:16.0.1'
    compile 'com.google.firebase:firebase-messaging:17.0.0'
  }

  apply plugin: 'com.google.gms.google-services'

You also need to modify the top level build.gradle

build.gradle

  buildscript {
      repositories {
          google()
          jcenter()
      }

      dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
        classpath 'com.google.gms:google-services:4.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
      }
  }

  allprojects {
      repositories {
          google()
          jcenter()
      }
  }

The important parts are highlighted in bold. Please note that you can't switch the order of google() and jcenter() repositories. Otherwise it won't work.

After that, you have to copy the google-services.json file to the app folder of your Android application

Get the Token

In order to get the token, we need to create a service that extends FirebaseInstanceIdService. Then override onTokenRefresh method. That metod will be called everytime a new token generated, usually at the first time the application runs after being installed. 

MyFirebaseIDService.java

  import android.util.Log;

  import com.google.firebase.iid.FirebaseInstanceId;
  import com.google.firebase.iid.FirebaseInstanceIdService;

  public class MyFirebaseIDService extends FirebaseInstanceIdService {
      @Override
      public void onTokenRefresh() {
          String refreshedToken = FirebaseInstanceId.getInstance().getToken();
          Log.d("FIREBASE_TOKEN", refreshedToken);

          // TODO: Implement the code for sending the token to the server.
      }
  }

Handle Rececived Notification Message

MyFirebaseMessagingService.java

  import android.util.Log;

  import com.google.firebase.messaging.FirebaseMessagingService;
  import com.google.firebase.messaging.RemoteMessage;

  public class MyFirebaseMessagingService extends 
  FirebaseMessagingService {
      private static final String TAG = "FCM Service";

      @Override
      public void onMessageReceived(RemoteMessage remoteMessage) {
        RemoteMessage.Notification notification = remoteMessage.getNotification();
        Log.d("FIREBASE_NOTIFICATION", "Title: " + notification.getTitle());
        Log.d("FIREBASE_NOTIFICATION", "Body: " + notification.getBody());

        // TODO: Handle received message.
    }
}

Try Sending Message From Firebase Console

To test whether you've set up everything correctly, you can try to send some messages to the devices. Click on Cloud Messaging menu on the sidebar of Firebase console. Then click on "Send your first message" button.

Firebase Cloud Messaging Console

For sending notification, you're required to enter the notification text and optionally you can enter the notification title and label. After that, click on "Test on device".

Firebase Cloud Messaging Send Notification

Enter the registration token on the popup and click on "Test" button.

Firebase Cloud Messaging Test on Device

If you've set up everything correctly, you should get a notification on the device. In case you want to know how to send a push notification using Firebase from your server, we have a tutorial on how to send notification to Firebase using Node.js.