Firebase Notification is a free service by Google for sending messages to mobile devices using Firebase Cloud Messaging(FCM). FCM provides an well maintained platform to send notifications that appears on the system tray of the devices. In this article we will discuss about the implementation of FCM in android devices.

Firebase Setup

If you are using Android Studio(version>2.2 or later) we will recommend using Firebase Assistant. Still it can be added manually. We will discuss both of them.

Using Firebase Assistant

Go to Tools from menu bar.

from menu bar. Click Firebase . Assistant window will open on the right hand side with different options like Analytics, Cloud Messaging, Authentication etc.

. Assistant window will open on the right hand side with different options like Analytics, Cloud Messaging, Authentication etc. Select Cloud Messaging .

. And then Set up Firebase Cloud Messaging.

After all the above steps you completed you will find 4-5 actions/steps there like Connect to Firebase, Add FCM to your app, Access the device registration token, Handle messages etc. which we will elaborate while discussing “adding Firebase manually”.

Add Firebase to your app manualy

Setting up Firebase from Firebase Assistant is very easy as we saw in the last paragraph. Still you can add it manually. To achieve it manually, you need to go through the following instructions

First of all, you need to create a Firebase project from Firebase Console. Or you can or import a Google project if you already have one.

if you already have one. Then click to ‘ Add Firebase to your app’ .

. It will ask you to create or select package name for your app.

Next you need to download configuration file. A google-services.json file will be downloaded.

file will be downloaded. After downloading the google-services.json file copy it to your project’s app folder(module).

Firebase is set up. Next we will integrate the SDK in your app.

Integrate SDK

Go to build.gradle(root level) and add the following rule

build.gradle(root) buildscript { .... .... dependencies { .... classpath 'com.google.gms:google-services:3.0.0' } } 1 2 3 4 5 6 7 8 9 10 11 12 buildscript { . . . . . . . . dependencies { . . . . classpath 'com.google.gms:google-services:3.0.0' } }

Next you need to add the following depedencies in your app level build.gradle file.

build.gradle(app) apply plugin: 'com.android.application' android { ... } dependencies { ... compile 'com.google.firebase:firebase-core:10.0.1' compile 'com.google.firebase:firebase-messaging:10.0.1' } apply plugin: 'com.google.gms.google-services' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 apply plugin : 'com.android.application' android { . . . } dependencies { . . . compile 'com.google.firebase:firebase-core:10.0.1' compile 'com.google.firebase:firebase-messaging:10.0.1' } apply plugin : 'com.google.gms.google-services'

Sync your Project and make sure no error occurs. Wait for the Gradle Sync to finish.

Firebase dependencies is added to your project. Version code(10.0.1 for now) may vary while you

will be adding dependencies to your project.

Edit Mainfest

Now we will add a service ‘AppFCMService‘ in AndroidManifest.xml. This extends FirebaseMessagingService . We need this to receive downstream messages, send upstream messages, recieve payload from server or Firebase console, show push notifications when the app is in foreground/background. Copy the following snippet before closing <application> tag of your AndroidManifest.xml file.

AndroidManifest.xml <service android:name=".AppFCMService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service> 1 2 3 4 5 6 7 8 9 10 11 <service android : name = ".AppFCMService" android : exported = "false" > <intent-filter> <action android : name = "com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>

Another service we need to create, for say ‘AppFirebaseInstanceIdService‘ which extends FirebaseInstanceIdService. This is required create/update registration tokens. Registration tokens are used to send messages to specific device or group of devices. Copy the following code like you did earlier in AndroidManifest.xml

AndroidManifest.xml <service android:name=".AppFirebaseInstanceIDService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> </intent-filter> </service> 1 2 3 4 5 6 7 8 9 10 11 <service android : name = ".AppFirebaseInstanceIDService" android : exported = "false" > <intent-filter> <action android : name = "com.google.firebase.INSTANCE_ID_EVENT" /> </intent-filter> </service>

OPTIONAL

Also you can set default icon,color of the notification by adding the following code snippet in your manifest.

AndroidManifest.xml <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_notification" /> <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/colorAccent" /> 1 2 3 4 5 6 7 8 9 10 <meta-data android : name = "com.google.firebase.messaging.default_notification_icon" android : resource = "@drawable/ic_notification" /> <meta-data android : name = "com.google.firebase.messaging.default_notification_color" android : resource = "@color/colorAccent" />

Generate FCM Token

Next we will implement the service AppFirebaseInstanceIDService which we declare earlier in AndroidManifest.xml . Just create a new class(Make sure the class should be created within the root directory of your app) and copy the following code.

AppFirebaseInstanceIDService.java package com.digitstory.testapplication; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; public class AppFirebaseInstanceIDService extends FirebaseInstanceIdService{ private final static String TAG="FCM Token"; @Override public void onTokenRefresh() { // Get updated InstanceID token. String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.d(TAG, "Refreshed token: " + refreshedToken); sendRegistrationToServer(refreshedToken); } private void sendRegistrationToServer(String token){ // TODO: Implement this method to send any registration to app's server. } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 package com . digitstory . testapplication ; import android . util . Log ; import com . google . firebase . iid . FirebaseInstanceId ; import com . google . firebase . iid . FirebaseInstanceIdService ; public class AppFirebaseInstanceIDService extends FirebaseInstanceIdService { private final static String TAG = "FCM Token" ; @Override public void onTokenRefresh ( ) { // Get updated InstanceID token. String refreshedToken = FirebaseInstanceId . getInstance ( ) . getToken ( ) ; Log . d ( TAG , "Refreshed token: " + refreshedToken ) ; sendRegistrationToServer ( refreshedToken ) ; } private void sendRegistrationToServer ( String token ) { // TODO: Implement this method to send any registration to app's server. } }

In the above code we are getting the FCM token automatically(whenever token is refreshed) in onTokenRefresh() method. After that we are sending it to our app’s server. So that we can store and send downstream message from server using that token.

Receive Message and Show Notification

Here we come with the most awaited functionality i.e. receiving and displaying push notification. We will implement the service AppFCMService mentioned earlier to achieve our goal. Here we go –

AppFCMService.java package com.digitstory.testapplication; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.media.RingtoneManager; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import java.util.Map; public class AppFCMService extends FirebaseMessagingService{ private final static String TAG="FCM Message"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { Log.d(TAG, "From: " + remoteMessage.getFrom()); Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody()); showNotification(remoteMessage); } private void showNotification(RemoteMessage remoteMessage){ String title=remoteMessage.getNotification().getTitle(); String body=remoteMessage.getNotification().getBody(); Intent intent=new Intent(this,MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , intent, PendingIntent.FLAG_ONE_SHOT); Bitmap notifyImage = BitmapFactory.decodeResource(getResources(), R.drawable.ic_notification); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_notification) .setLargeIcon(notifyImage) .setColor(Color.parseColor("#FFE74C3C")) .setContentTitle(title) .setContentText(body) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0, notificationBuilder.build()); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 package com . digitstory . testapplication ; import android . app . NotificationManager ; import android . app . PendingIntent ; import android . content . Context ; import android . content . Intent ; import android . graphics . Bitmap ; import android . graphics . BitmapFactory ; import android . graphics . Color ; import android . media . RingtoneManager ; import android . net . Uri ; import android . support . v4 . app . NotificationCompat ; import android . util . Log ; import com . google . firebase . messaging . FirebaseMessagingService ; import com . google . firebase . messaging . RemoteMessage ; import java . util . Map ; public class AppFCMService extends FirebaseMessagingService { private final static String TAG = "FCM Message" ; @Override public void onMessageReceived ( RemoteMessage remoteMessage ) { Log . d ( TAG , "From: " + remoteMessage . getFrom ( ) ) ; Log . d ( TAG , "Notification Message Body: " + remoteMessage . getNotification ( ) . getBody ( ) ) ; showNotification ( remoteMessage ) ; } private void showNotification ( RemoteMessage remoteMessage ) { String title = remoteMessage . getNotification ( ) . getTitle ( ) ; String body = remoteMessage . getNotification ( ) . getBody ( ) ; Intent intent = new Intent ( this , MainActivity . class ) ; PendingIntent pendingIntent = PendingIntent . getActivity ( this , 0 , intent , PendingIntent . FLAG_ONE_SHOT ) ; Bitmap notifyImage = BitmapFactory . decodeResource ( getResources ( ) , R . drawable . ic_notification ) ; Uri defaultSoundUri = RingtoneManager . getDefaultUri ( RingtoneManager . TYPE_NOTIFICATION ) ; NotificationCompat . Builder notificationBuilder = new NotificationCompat . Builder ( this ) . setSmallIcon ( R . drawable . ic_notification ) . setLargeIcon ( notifyImage ) . setColor ( Color . parseColor ( "#FFE74C3C" ) ) . setContentTitle ( title ) . setContentText ( body ) . setAutoCancel ( true ) . setSound ( defaultSoundUri ) . setContentIntent ( pendingIntent ) ; NotificationManager notificationManager = ( NotificationManager ) getSystemService ( Context . NOTIFICATION_SERVICE ) ; notificationManager . notify ( 0 , notificationBuilder . build ( ) ) ; } }

This service consists of two methods

1. onMessageReceived() : Whenever message is received this method is invoked.

2. showNotification() : Display the notification.

In onMessageReceived() method we are receiving the data(RemoteMessage) from the server or Firebase console. Then we pass it to showNotification() method to build and show the notification(as shown in the picture).

The data can be sent from both Firebase console or your custom server. To send from your custom server you need to implement FCM in your server(built in PHP or Node.js etc) Read this article.