C1CTech

Android Firebase Cloud Messaging Example

What is Firebase Cloud Messaging?

It is a service provided by Google. Google says  “Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost.”

So it is free and at the same time easy to use. Previously we were using Google Cloud Messaging, but nowadays GCM is obsolete. So you should use firebase only.

 

Message Types

Before moving ahead in the post let’s first understand the types of message that can be sent using FCM.

  1. Notification Message: Notification messages are handled by firebase SDK itself. Typically the notification message contains title, message, icon etc., These message can be sent from firebase console UI. By sending this kind of messages, you won’t get much control over the notification.This type of message is automatically displayed to end user. In this kind of message, we have a predefined set of key-value pairs. We also have a data payload by using it we can set the custom key-value pairs as well.
  2. Data message: Default does not display this type of message to the end user. To show it we need to add some coding. This message contains only custom key-value pairs.

Adding Firebase Cloud Messaging to Android Project

Creating a new Android Studio Project

Adding Firebase Cloud Messaging

 

 

Connect to Firebase

 

 

 

Add FCM to your app

 

 

Ways of Receiving Push Notification

Now first, we need to understand how we receive or send notifications using FCM. So there are two ways.

  1. Using FCM Token: We use this method when we want to send a notification to a specific device. Or some dynamic group of devices. Upon initial startup, the firebase SDK generates a registration token for the application. We use this token to identify the device.
  2. Using Topic: We can create topics and let our users subscribe to those topics. Then we can send the message to the topic. And the message will be sent to all the users of that particular topic. In this method, we don’t need to store any token.

We can select from the above two methods to implement in our application. Here we will learn about the FCM Token .

Firebase Cloud Messaging using FCM Access Token

In this method first, we will generate the access token. Now to get the access token, we create a class that extends FirebaseInstanceIdService. It is a service that we also need to define inside our Manifest file. Now let’s see how we can do this in our project.

Generating Access Token

MyFirebaseInstanceIdService.Java

package com.c1ctech.firebasepushnotificationexample;

import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;


public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {

    //this method will be called
    //when the token is generated
    @Override
    public void onTokenRefresh() {

        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        //for now we are displaying the token in the log
        //copy it as this method is called only when the new token is generated
        //and usually new token is only generated when the app is reinstalled or the data is cleared

        Log.d("Refreshed token: ", refreshedToken);


    }
}
package com.c1ctech.firebasepushnotificationexample;

public class Constants {

    public static final String CHANNEL_ID = "my_channel_01";
    public static final String CHANNEL_NAME = "Simplified Coding Notification";
    public static final String CHANNEL_DESCRIPTION = "www.simplifiedcoding.net";
}

MyNotificationManager.Java

package com.c1ctech.firebasepushnotificationexample;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

import static android.content.Context.NOTIFICATION_SERVICE;


public class MyNotificationManager {

    private Context mCtx;
    private static MyNotificationManager mInstance;

    private MyNotificationManager(Context context) {
        mCtx = context;
    }

    public static synchronized MyNotificationManager getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MyNotificationManager(context);
        }
        return mInstance;
    }

    public void displayNotification(String title, String body) {

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(mCtx, Constants.CHANNEL_ID)
                        .setSmallIcon(R.drawable.app_icon)
                        .setContentTitle(title)
                        .setContentText(body);


        /*
         *  Clicking on the notification will take us to this intent
         *  Right now we are using the MainActivity as this is the only activity we have in our application
         *  But for your project you can customize it as you want
         * */

        Intent resultIntent = new Intent(mCtx, MainActivity.class);

        /*
         *  Now we will create a pending intent
         *  The method getActivity is taking 4 parameters
         *  All paramters are describing themselves
         *  0 is the request code (the second parameter)
         *  We can detect this code in the activity that will open by this we can get
         *  Which notification opened the activity
         * */
        PendingIntent pendingIntent = PendingIntent.getActivity(mCtx, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        /*
         *  Setting the pending intent to notification builder
         * */

        mBuilder.setContentIntent(pendingIntent);

        NotificationManager mNotifyMgr =
                (NotificationManager) mCtx.getSystemService(NOTIFICATION_SERVICE);

        /*
         * The first parameter is the notification id
         * better don't give a literal here (right now we are giving a int literal)
         * because using this id we can modify it later
         * */
        if (mNotifyMgr != null) {
            mNotifyMgr.notify(1, mBuilder.build());
        }
    }

}

Testing a Local Notification

Before moving ahead, we will confirm that the notification is working correctly. For this, we will create a local notification from the app itself.

 

package com.c1ctech.firebasepushnotificationexample;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        //If the device is having android oreo we will create a notification channel

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationManager mNotificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(Constants.CHANNEL_ID, Constants.CHANNEL_NAME, importance);
            mChannel.setDescription(Constants.CHANNEL_DESCRIPTION);
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mNotificationManager.createNotificationChannel(mChannel);
        }

        //Displaying a notification locally
        MyNotificationManager.getInstance(getApplicationContext()).displayNotification("Hi","Where are you?");


    }
}

 

 

Testing Notification from Firebase Console

 

 

 

 

 

 

Exit mobile version