FCM Notifications with 26+

Firebase cloud messaging is a cross-platform messaging solution from which one can notify clients about new emails and engage users with the App at no cost. This blog assumes that you have linked firebase to your android project.

Let’s begin with the prerequisites:

  • Update or install the latest version of Android Studio 
  • Targets API level 16 and above 
  • Uses gradle 4.1 and higher
  • Uses Jetpack (AndroidX)

Concerning receiving fCM messages, the app should write a service which is implementing the FirebaseMessagingService.

FCM uses tokens that are encrypted, are in alphanumeric form and are unique for a device. These tokens are generated when the user launches the app for the first time, or when it clears the app’s data, or when it deletes the token. 

The FCM service will be triggered when the token changes for your device or generated for the first time. To work with the new token, one has to override onNewToken of FirebaseMessagingservice.

One has to register the service in the android manifest file and must include internet permission.

For API 26 and above, notification channel is required which allows users to modify it from device notification settings. It should be named as:

The notification channel is pertinent to API 26 above and therefore include the below statement in your code:

And this is how you can achieve a notification channel:

When a message is sent, onMessageReceived method of FirebaseMessagingService is triggered. For API 26+ add the following code inside the onMessageReceived method to handle the message received.

For devices below API level 26:

Overall code covering all the API levels will look like:

One should check the API level of the device to choose an appropriate way to work with the notifications. Once the channel is passed to the notification manager, it is now in control of the user to modify its channels through settings, like setting for sound, priority, colour, etc. For code on how to create a channel considering Android 8 and above example, follow the link: https://github.com/android/user-interface-samples/tree/main/Notifications

This is how one can achieve FCM notification for API  26+. For testing purposes use firebase platform to send text messages which can be specific to the user(specific to the token), or to a group of devices. For more information refer to the link https://firebase.google.com/docs/cloud-messaging/android/client.

Leave a Reply