For this third article, I suggest explain you how to implement push notifications service within your android application. In the most of applications it is amazing to find an application on the playstore which doesn’t use the google services to encourage users returning on the android application. So it seemed interesting to me to go back on the different stages which constitutes the implementation of such a service.

Prerequisites

To use the Firebase services that allow you a token generation then register your device with your push notifications service, add the two following dependencies to your app.build.gradle configuration file :

dependencies {
  ...
  compile 'com.google.firebase:firebase-core:10.2.0'
  compile 'com.google.firebase:firebase-messaging:10.2.0'
  ...
}

Add now the google messaging services (gms) plugin at the bottom of your app.build.gradle configuration file :

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

Open the build.gradle file and place it in the buildscript.dependencies part. Add the following line classpath 'com.google.gms:google-services:3.0.0' as explained in the example below:

buildscript {
  dependencies {
    classpath 'com.google.gms:google-services:3.0.0'
  }
}

Note : At each step of your modifying build files, your IDE should prompt you to synchronize your changes with the latest know project version. In a successful case, you can move on to the next step, otherwise, you have to verify you correctly have follow the previous steps and try again if necessary. In the case of new synchronization failed, review the error message, check version dependencies, and be sure they are compatible with the rest of the project.

Firebase token generation

As previously explained in this article’s introduction in order for your notification service send an alert on your device, you must register it with your notification service. To do this, you’ll need to make a call to your WS to provide him with a tokken identifier which will allow this to identify your device. If this identifier is not known to your remote service notification, your device will never be able to receive notifications.

try {
  String refreshedToken = FirebaseInstanceId.getInstance().getToken();
  Log.d("Firbase id login", "Refreshed token: " + refreshedToken);
  prefManager.setStringInPreferences(ApplicationConstants.FIREBASE_TOKEN,refreshedToken);
} catch (Exception e) {
  e.printStackTrace();
}

I advise you to generate your token once, then save it in the device preferences. This will make it more simple to allow or disallow notifications on the device.

The reception service

At this step, we generated a Firbase token, and registered it with to the push notifications service (no detailed step). We only had to set up the reception service and define different implementation cases according different android application states (resumed / paused / destroyed )

Declare the service

Now, I suggest you to go in the manifest.xml configuration file of your android application and add the following lines :

<service android:name="com.myapplication.services.MyFirebaseMessagingService">
  <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT" />
  </intent-filter>
</service>

Here, we declare our service MyFirebaseMessagingService that hasn’t been yet implemented. Without these lines, the service will never start and you’ll never receive notifications from your notification service.

Create the service

Place yourself at the level of the desired tree (in our case: com.myapplication.services) and create a MyFirebaseMessagingService.java named class.

public class MyFirebaseMessagingService extends FirebaseMessagingService {
  ...
}

Receive the notification

Override the onMessageReceived() method like this :

public class MyFirebaseMessagingService extends FirebaseMessagingService {
  private static final String TAG = "MyFirebaseMsgService";
  private RemoteMessage remoteMessage;
  @Override
  public void onMessageReceived(RemoteMessage remoteMessage) {
    Map<String,String> map = remoteMessage.getData();
    String dataString = map.get("data").toString();
    displayNotification(dataString);
  }
  ...
}

The MyFirebaseMessagingService class inherits from com.google.firebase.messaging.FirebaseMessagingService and we override the onMessageReceived method which will be automatically called when a new notification will be sent to your device at the condition it has been registered to your push notifications service. Note: Notifications must be open according to 3 states of your application: foreground, background or destroyed. In case your application is in foreground, no particular worries, test to send a notification on your device you should receive it successful. However, when you change your application state to the background state (onPause ()) or destroyed () then it is another nothing is over !

Why is this happening ?

There are two types of messages in FCM (Firebase Cloud Messaging):

Send to specific devices :

{
  "data": {
    "my_custom_key" : "my_custom_value",
    "other_key" : true
  },
  "registration_ids": ["{device-token}","{device2-token}","{device3-token}"]
}

Like this you will be able to receive your push notification as in foreground state than destroyed or paused state. Note : don’t forget to change the value in your « onMessageReceived » when you get your json object by the following line :

String dataString = map.get("data").toString();

Display the notification

At this point your application is able to detect when a notification has been received on your device from your remote notification service. The main of all this is to be able display received notification. To do this, add the “DisplayNotification (dataString)” method in the “MyFirebaseMessagingService.java” class. It will be called from the “onMessageReceived” method.

private void displayNotification(String remoteMessage) {
  Intent intent = new Intent(this, MainActivity.class);
  intent.setAction("android.intent.action.MAIN");
  intent.addCategory("android.intent.category.LAUNCHER");
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
  intent.putExtra(ApplicationConstants.DATA_JSONEOUESTION_RESPONSES, remoteMessage);
  PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
  Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

  NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
  .setSmallIcon(R.mipmap.apple)
  .setContentTitle(«My title »)
  .setContentText(« Congratulation, You've receive a new notification !)
  .setAutoCancel(true)
  .setSound(defaultSoundUri)
  .setDefaults(android.app.Notification.DEFAULT_ALL)
  .setPriority(android.app.Notification.PRIORITY_HIGH)
  .setContentIntent(pendingIntent);

  NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  notificationManager.notify(0, notificationBuilder.build());
}

First, we create an intent that will be used to define the activity to open when push notification is clicked by the user. To do this, we have to use a Pending Intent which will take the intent parameter we have previously defined then set as a parameter of the .”setContentIntent” method of the “NotificationCompat.Builder.Object”. Continue by the creating the notification with all necessaries parameters to customize and display it with the next line :

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

Conclusion

Push notification represents an unavoidable step of a android application development. In this article, we’ve seen how generate a Firebase token after have declared the appropriate google dependencies. To continue, we have created the reception service notification after have declared this in the manifest configuration file. To follow ,we’ve seen why your device may not received notification when your application will could be on paused or destroyed state et how to resolve this. To finish, we describe the method that let to display notification on the user device and corresponding actions to implements to open the wished activity. I hope this new article enjoy help you in your android development ! Don’t hesitate write a comment about this or to share your personal experience concerning this subject !