Firebase Push notification using Android and Firebase cloud messaging Tutorial

Implement a push notification to an Android smartphone using Firebase. This Android tutorial guides you step by step how to integrate an Android app with Firebase push notification

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

  • Authentication
  • Remote config
  • Crash reporting

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

What is Firebase push notification?

Before digging into the details of how to send Firebase push notification in Android using Firebase cloud messaging, it is useful to clarify what is push notification. For example, through push notification, our app can notify a user of new events. This happens even if the Android app is not working in the 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 Firebase push notification in Android, 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 an Android 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)

If you are eager to test the Android app, you can use the link below to download the Android app source code: 

The video below shows how the app works when receiving an Android notification:

Set up Firebase cloud messaging project in Firebase console

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 of 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. In the end, you get a json file that you have to copy at the app module level.

How to implement push notification in Android using Firebase

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 shown below:

[xml] buildscript {
repositories {
jcenter()
}
dependencies {
classpath ‘com.android.tools.build:gradle:<latest version>’
classpath ‘com.google.gms:google-services:<latest version>’
}
}[/xml]

and at the module level:

[xml] ….
dependencies {
…..
compile ‘com.android.support:appcompat-v7:<latest version>’
compile ‘com.google.firebase:firebase-messaging:<latest version>’
}

apply plugin: ‘com.google.gms.google-services'[/xml]

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.

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

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

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, the Android service overrides the onTokenRefresh method.

[java] public class FireIDService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
String tkn = FirebaseInstanceId.getInstance().getInstanceId();
Log.d("Not","Token ["+tkn+"]");
}
}
[/java]

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 server stores it somewhere.
Do not forget to declare this service in the Manifest.xml.

[xml] ..
<service android:name=".FireIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
[/xml]

Finally, we implement the service that handles incoming push notification:

[java] public class FireMsgService extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);

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

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

NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle("Message")
.setContentText(remoteMessage.getNotification().getBody())
.setAutoCancel(true)
.setContentIntent(pendingIntent);

NotificationManager notificationManager =
(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);

notificationManager.notify(1410, notificationBuilder.build());
}
}
[/java]

In onMessageReceived method, we simply show the notification containing the message sent.

How to use Firebase API

An interesting aspect is the 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 first step is getting the Firebase authentication key so that we can authenticate the client. As a 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 a 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 of how to use push notification in Android using Firebase. We have developed an Android app that receives Android notifications. Moreover, we have discovered how to configure Firebase to handle push notification. Finally, we have covered how to use Firebase API and how to integrate Firebase with an external system using these APIs.

You can expand further this project and handle different scenarios. Firebase Push notifications in Android are very useful and an Android app can use them every time is necessary to send an alert to users. There are several scenarios where Android notification can be integrated with Internet of Things: alert related to environmental monitoring or production systems and so on.

Once you know how to handle push notification in Android you have countless possibilities.

    1. Sanal MS November 25, 2016
    2. Purvik Rana November 28, 2016
      • Francesco Azzola December 6, 2016
      • hopewise June 7, 2017
    3. Yashvir Singh December 30, 2016
      • Francesco Azzola December 30, 2016
    4. Simon Cantor February 7, 2017
    5. Kumar Alok February 18, 2017
    6. Orlay Garcia Duconge June 4, 2017
    7. Aro Wolfgang Micheal October 31, 2017
    8. mohamed sayed November 8, 2017
    9. Amit Pandey June 21, 2019
    10. Albert November 18, 2019
    11. Francesco Azzola November 22, 2019
    12. Anonymous December 12, 2019
    13. Black Gold January 11, 2020
    14. MesMey 24TI January 21, 2020
    15. ROCK_Kumar March 6, 2020
    16. WonderPush March 12, 2020

    Add Your Comment