Push notification in Android using Firebase cloud messaging

This post covers how to send push notification using Android Firebase.  In the past, we were used to send push notification in Android using Google Cloud messaging service. Recently, it was introduced a new way to send push data using Android Firebase. Even if the basic principles remain the same Firebase introduced some interesting new features. Firebase supports other services like:

  • Authentication
  • Remote config
  • Crash reporting

This post will cover step by step how to send a push notification from Firebase console to an app.

What is push notification?

Before digging into the details how to send notification in Android, it is useful to clarify what is a push notification. Using Android push notification, our app can notify a user of new events. This happens even if our app is not working in foreground. Using this service, we can send data from our server to our app whenever a new event occurs. This paradigm is much more efficient respect to keep on connecting to the server (pull method) to ask if there are new events.

Using push notification, we can keep the user informed about events without draining the smartphone battery. When a user receives the notification, it appears, as a customized icon, in the status bar. There are different paradigms to use when sending a push notification:

  Message to a single device

 Message to a topic (send the same message to the multiple devices subscribed to a specific topic. This implements the model publisher/subscribers)

 Message to a group (multiple devices that share the same key used to identify a smartphone)

android push notification using firebase

Set up Firebase cloud messaging project

It is time to start! Create an account to access to Firebase console and define a project:

android firebase create new project

and then:

android firebase project

Once you have created your project, you have to add the package name of your app. Be aware using the same package name in Android Studio and in the Firebase console:

create android firebase app

At the end of this process, your project is configured on Firebase and you are ready to develop your Android Firebase app. At the end, you get a json file that you have to copy at app module level.

Want to make your app more secure?
Read this tutorial about how to use fingerprint authentication in Android.

How to implement Android Firebase push notification

Now we can develop the Android app integrated with Firebase. As a first step, we have to add Firebase to our app and modify gradle files. At the project level let’s modify gradle fille as:

buildscript {
    repositories {
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.3'
        classpath 'com.google.gms:google-services:3.0.0'

and at the module name (usually named app):

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.google.firebase:firebase-messaging:9.4.0'

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

In this case, we added messaging dependency. Once the gradle files are configured, the next step is creating our app. In the MainActivity we add a Button to get the current token. This token is important because we use it in the Firebase console, to set the right destination device.

You can learn more about how to use Firebase to real-time data syncronization

Let us suppose, we have already defined the layout containing the button, in the Activity class:

Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
      String tkn = FirebaseInstanceId.getInstance().getToken();
      Toast.makeText(MainActivity.this, "Current token ["+tkn+"]",
      Log.d("App", "Token ["+tkn+"]");

Notice we used FirebaseInstanceId singleton to the get the current instance and then the current token. It may take a while before the token is generated, so you could get a null value at the beginning.
Moreover, we can monitor the token creation process and get notified when it is available using a custom service that extends FirebaseInstanceIdService. In this case we override the onTokenRefresh method.

public class FireIDService extends FirebaseInstanceIdService {
    public void onTokenRefresh() {
        String tkn = FirebaseInstanceId.getInstance().getToken();
        Log.d("Not","Token ["+tkn+"]");


In this method, we just log the token, but it could be used in a real app to send the token to the server so that the serve stores it.
Don’t forget to declare this service in the Manifest.xml.

<service android:name=".FireIDService">
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>

At the end, we implement the service that handles incoming push notification:

public class FireMsgService extends FirebaseMessagingService {

    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d("Msg", "Message received ["+remoteMessage+"]");

        // Create Notification
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410, 
                        intent, PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder notificationBuilder = new

        NotificationManager notificationManager =

        notificationManager.notify(1410, notificationBuilder.build());

In onMessageReceived method, we simply show the notification containing the message sent.
Running the app, we get the result shown in the video below:

Firebase API

An interesting aspect is Firebase API. In other words, it is possible to invoke Android Firebase services using API. This is very interesting because we can integrate Firebase with external systems.
In this example, we will show how to send a notification invoking Firebase API. The fist step is getting the Firebase authentication key so that we can authenticate the client. As client we will use Postman but we can use other clients too. How to get the authentication key? Well you get it from Firebase console:

google firebase api

Once we have the authentication key we can create our message:

google firebase api header

and as body:

google firebase json api body

Notice that to contains the smartphone token (described above).
Finally sending the message, we get as result:

google firebase json response

And the notification appears on the destination smartphone.

At the end of this post, you gained the knowledge how to use push notification using Android Firebase.

Source code available @github.

More posts...
  • Sanal MS

    Thanks for your detailed tutorial. I have implemented this and working fine except the device not receiving push if the app force closed. Do you have any idea about this? If I force close app it does not receive push.

    Sanal MS

  • Purvik Rana

    From where we can create our message to send?
    Is it require to set up server on our hosting for it or we can access it form some where else on Firebase console. Please let me know about it.

    • Can you explain? You can access Firebase using a client that wants to send notifications.
      If you want to test it, you can use the Firebase console.

    • hopewise

      Did you have an answer of your question?

  • Yashvir Singh

    The request was missing an Authentification Key (FCM Token). Please, refer to section "Authentification" of the FCM documentation, at https://firebase.google.com/docs/cloud-messaging/server.

    The request was missing an Authentification Key (FCM Token). Please, refer to section "Authentification" of the FCM documentation, at https://firebase.google.com/docs/cloud-messaging/server.
    Error 401

    • I guess you didn’t follow al the steps in the tutorial. You are missing the Key you get from the console

  • Simon Cantor

    Google provides exceptionally bad explanations from tool to tool.
    Sometimes I ask myself do they want to make the tools usable.
    The very simple case :
    I want to send message to a topic. Can I do this way of FirebaseMessaging.sendMessage(RemoteMessage r)??
    I don’t see any simple manual, example, header list, how I must define the topic in builder. Firebase tool on Android Studio takes me to irrelevant information how to subscribe from link “send..”. The only simple question, can I build and send topic message, and which data header correspond to topic, which to body. No information.
    Anybody knows this?

  • Kumar Alok

    thanks ..it work

  • Orlay Garcia Duconge

    If the app is in the background, I can’t set LargeIcon to notificationBuilder because onMessageReceived is not called.

  • Aro Wolfgang Micheal

    i love you for this….. i really do… straight to the point, effective, effiecient and powerful. i love you once again…. i just bookmarked your website…. 🙂 ..if only i could pay you enough.

  • mohamed sayed

    is there a way to send the notification at specific time

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.