Push Notification on Android Using Firebase Cloud Messaging

Push Notification on Android Using Firebase Cloud Messaging

Push notifications are the very useful way to keep your user engagement by sharing the valuable information to the user. So today in this tutorial we implement the Push Notification for Android App. This tutorial has two parts

  • First Create the Project and setup the Project on Firebase Cloud Messaging
  • Second Implement the Code on Android App

So let’s start the action and create a Simple Project in Android Studio and give a nice name like Push Notification.

Setup the Firebase Cloud Messaging

So before starting the coding for your app, you need to create a project on google firebase cloud. So kindly go the firebase console.

If you don’t create the any project before then you have to create a new project inside the firebase console. So input the details of your project like given below and create the project.

Push Notification Create Project

Once you have created the project as above then we have to create the app by selecting the type as android as given below.

Push Notification in Android

After the above steps, you will get the option to download the JSON format configuration files. Download and save the file we will use this later in our project when we start the coding part.

Push Notification in Android

Add Firebase Cloud Messaging to your project

Now we have to configure our project to use the Firebase Cloud Messaging API. It was shown in the steps three of the above steps which are given below.

The Google services plugin for Gradle loads the google-services.json file you just downloaded. Modify your build.gradle files to use the plugin.

Project-level build.gradle (<project>/build.gradle):

buildscript {
dependencies {
// Add this line
classpath 'com.google.gms:google-services:3.2.0'
}
}

App-level build.gradle (<project>/<app-module>/build.gradle):

dependencies {
// Add this line
compile 'com.google.firebase:firebase-core:11.8.0'
}
...
// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'

Finally, press “Sync now” in the bar that appears in the IDE:

After the above steps kindly move the downloaded JSON format config files to your project app/ location and click on make project from build menu of the IDE.

In case if you have not downloaded the configuration file you can download the same by going into the project setup menu again.

Create Firebase Message Service

We need to create a service by extending the firebase message service class. It will help the handling of the notification inside your app. This is very simple default implementation of the Firebase Message Service Push Notification.

package com.nplix.firebasepushnotification;

import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

/**
 * Created by PK on 2/28/2018.
 */

public class MyMessagingService extends FirebaseMessagingService {
public static String TAG="MyMessaging Service";
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
       
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
              //  scheduleJob();
            } else {
                // Handle message within 10 seconds
              //  handleNow();
            }

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

    }
}

Add this service to your AndroidMainfest.xml file

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

Create the Firebase Instance ID Service

This service helps us to get the latest token from firebase.

package com.nplix.firebasepushnotification;

import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

/**
 * Created by PK on 2/28/2018.
 */

public class MyInstanceIDService extends FirebaseInstanceIdService {
  public static String TAG="Push Notification";
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

    }
}

Let’s add the service to the AndroidMainfest.xml file as given below.

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

Test the app by sending the Notification from Firebase Cloud console

We have done the sample implementation of the Push Notification using Firebase Cloud Messaging. Now we are ready to test the same. So go to Firebase Cloud console and create a message and scroll down to bottom of side menu and click on the notification menu. Then click on send your first message as like screenshots given below.

Push Notification firebase cloud console

After this, you will get the screen to create your push notification as below.

notification compose in Firebase Cloud Console

Type the notification and select the app on which you want to send the notification and click on the send message option.

Android Push Notification

 

You may have noticed that in the article we not done any modification in the main activity file as well. It is because all was handled by the service itself. However, if we go for the actual implementation of then we must have to handle lots of other things as well, which required the all the stuff.

We that’s all in the article, my friends. If you have any dought or question then please leave a comment below. If you think this article is helpful, don’t forget to hit the like and share button below. Thank you!

Get Email Updates!

Signup now receive an email once I publish new content. I will never give away, trade or sell your email address. You can unsubscribe at any time.

Join 911 other subscribers

Leave a Reply

Close Menu