Android Core

Push notification in Android using Firebase cloud messaging

This post covers how to send push notification in Android.  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 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 paradigm 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_firebase-1024x512

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

How to implement Android push notification with 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:

buildscript {
    repositories {
        jcenter()
    }
    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.
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() {
    @Override
    public void onClick(View view) {
      String tkn = FirebaseInstanceId.getInstance().getToken();
      Toast.makeText(MainActivity.this, "Current token ["+tkn+"]",
                     Toast.LENGTH_LONG).show();
      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 {
    @Override
    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">
     <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
     </intent-filter>
 </service>

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

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);
    }
}

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

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

Francesco Azzola

He's a senior software engineer with more than 15 yrs old experience in JEE architecture. He's SCEA certified (Sun Certified Enterprise Architect), SCWCD, SCJP. He is an android enthusiast and he has worked for long time in the mobile development field.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Smith Brad
3 years ago

Great Article! Thank you for sharing amazing information about the react native push notifications

Last edited 3 years ago by Smith Brad
Brad Smith
2 years ago

Thank you for sharing the Great Information about the reach native push notifications with us.

Back to top button