Android Push Notification Using Firebase and Advanced REST Client

Vikas Tomar
AndroidPub
Published in
7 min readDec 14, 2018
Photo by Jamie Street on Unsplash

After spending four days juggling between various resources, writing codes and deleting it again and again, I finally learned how to successfully implement Push Notification in android using Firebase and ARC in a not so complex way. Stick along as I walk you through the process.

So, before we get into coding and stuff let us develop a basic understanding of what are notifications and how do they work.

Notifications Overview

A notification is a message that Android displays outside your app’s UI to provide the user with reminders, communication from other people, or other timely information from your app. Users can tap the notification to open your app or take an action directly from the notification.

The design of a notification is determined by system templates — your app simply defines the contents for each portion of the template. Some details of the notification appear only in the expanded view.

The most common parts of a notification are indicated in figure 7 as follows:

Notification Anatomy
  1. Small icon: This is required and set with setSmallIcon().
  2. App name: This is provided by the system.
  3. Time stamp: This is provided by the system but you can override with setWhen() or hide it with setShowWhen(false).
  4. Large icon: This is optional (usually used only for contact photos; do not use it for your app icon) and set with setLargeIcon().
  5. Title: This is optional and set with setContentTitle().
  6. Text: This is optional and set with setContentText().

For more information about how to create a notification with these features and more, read Create a Notification.

Using Firebase Cloud Messaging you can send three types of messages i.e Notification Message, Data Message, and message with both Notification & Data Payload.

1. Notification Message:

Notification messages are handled by firebase SDK itself. Typically the notification message contains a title, message, icon etc., These messages can be sent from firebase console UI. By sending this kind of messages, you won’t get much control over the notification. The notification will be shown automatically when the app is in the background.

2. Data Message:

Data messages have to be handled by the Android app. You can add this kind of messages if you want to send some additional data along with the notification. But sending these messages through firebase console is not possible. You need to have a server-side logic to send the notification using Firebase API. You need to use data key when sending this message.

3. Messages with both notification and data payload:

A message can also contain both notification and data payload. When these kinds of messages are sent, it will be handled in two scenarios depending upon app state (background/foreground). For these messages, we can use both notification and data keys.

When in the background — Apps receive the notification payload in the notification tray and only handle the data payload when the user taps on the notification.

When in the foreground — App receives a message object with both payloads available.

Let’s Code

First things first, create a new project empty activity and add the Firebase dependencies for Cloud Messaging. You can find the latest dependencies in the Cloud Messaging Android Developer Docs over here. Or you can go the easy-peasy way by adding integrating the Firebase and Cloud messaging directly from the Android Studio. Go to Tools>FIrebase, select Cloud Messaging, and set it up.

Once done with the Firebase setup, we’ll get started with the coding part.

Create two packages, Congif, and Services. Now add the following Java classes:

  • Config: Config.java
  • Services: MyFirebaseInstanceService.java and MyFirebaseMessagingService.java
Creating new classes.

Config.java

This class is kind of helper class used to store some useful information retrieved from data being received from the server. It’s optional to create this class but I would suggest you create one to improve understandability of the app. This information is further used in the app at various places like displaying the notification title, notification content, image etc.

Setup this class as follow:

MyFirebaseInstanceService.java

On initial startup of your app, the FCM SDK generates a registration token for the client app instance. If you want to target single devices or create device groups, you’ll need to access this token.

You can easily access the token’s value by creating a new class which extends FirebaseInstanceIdService . In that class, call getToken within onTokenRefresh , and log the value as shown:

The onTokenRefress() callback fires whenever a new token is generated.

Also, add the services to your manifest file in the <activity> section:

<service
android:name=”.MyFirebaseInstanceIDService”>
<intent-filter>
<action android:name=”com.google.firebase.INSTANCE_ID_EVENT”/>
</intent-filter>
</service>

Now let’s get to the real part.

MyFirebaseMessagingService.java

If you wish to do any message handling beyond receiving notifications on apps in the background we need to create this create this service. It extends FirebaseMesasagingService. This service is necessary to receive notifications in foregrounded apps, to receive data payload, to send upstream messages, and so on.

Let me just explain you stepwise what we’re going to do in this

  1. First of all, we’ll create an onMessageRecieved() method to handle the incoming messages.
  2. We’ll perform a check if the message contains some data, if yes, we’ll forward it to next method i.e., getImage().
  3. In this method retrieve some useful information from the message and add it to the Config class variable. Also, we’ll be fetching an image to be displayed in the notification using the Piccaso library.
  4. Once the image has been fetched it’ll be passed on to the sendNotification() method and we’ll display the notification.

Don’t forget to add the Picasso library dependency:

implementation 'com.google.firebase:firebase-messaging:11.0.4'

Code for the class:

Finally, we’re done with the coding part.

Now we’ll move on to the Advanced REST Client part.

Advanced REST Client

Open up Google Chrome and download Advanced REST Client extension from the Chrome Web Store. ARC is a helper program to create and test custom HTTP requests.

Once downloaded setup the ARC as follows:

Setting Up ARC
  • In order to find your Server key or authorization key, go to Firebase Project Setting ->Cloud Messaging->ServerKey.

Once you have set up the headers, move to the Body tab and set it up as follow:

Setting up ARC Body

You can copy the JSON part from below:

{
“data”: {
“title”: “Hey”,
“content” : “Check Out This Awesome Game!”,
“imageUrl”: “http://h5.4j.com/thumb/Ninja-Run.jpg",
“gameUrl”: “https://h5.4j.com/Ninja-Run/index.php?pubid=noad"
},
“to”: “/topics/all”
}

This JSON contains the data payload that our message from the server to the device is going to contain and will be used to display the notification. All the keys are self-explanatory except the “to” key.

Let’s focus on this last “to” key-value pair for a while. This key-value pair specifies to whom are we going to send the notifications to. We might be targetting a single person, a segment of users of our app or the entire user base of our app.

In case we want to send the notification to a single user we replace the “to” value by the token generated by the device of the user.

In case we want to send notifications to all the users just leave the “to” value as it is in the code. Also, we need to add the following line to our MyFirebaseInstanceService.java class:

FirebaseMessaging.getInstance().subscribeToTopic(“all”);

You can always read more about topic messaging from here.

Now press the POST button in order to receive the notifications.

The appearance of received Notifications.

That’s it. Now, let your users know your presence and keep them engaged to your app. Till the next buzz…

Conclusion

Sending notification to a group of people isn’t as tough a task as it may seem at first. Understanding the working behind and reading Google’s Android Developer Docs surely give you an upper hand but at times might not provide you the just solution you’ve been looking for. I hope this article helped you to ease with the task of sending notifications.

Resources:

  1. https://developer.android.com/guide/topics/ui/notifiers/notifications
  2. https://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
  3. https://www.youtube.com/watch?v=82uwhCj3zuI

Do let me know about any mistakes that I made or any concept that I overlooked. Criticism and improvements are always welcomed.

--

--

Vikas Tomar
AndroidPub

Enthusiastic Android Developer | An UI/UX Design Dilettante |Data Science Beginner