fcm-icoderslab-notifications

Android Push Notifications using Firebase Cloud Messaging FCM

In this tutorial, we will learn “how to Push Android Notifications using Firebase Cloud Messaging FCM”
First of all, you should know about the concept of Firebase, Cloud Messaging, and FCM

Firebase:

Firebase is part of a growing trend known as “Backend as a service”. It is a technology that lets you compose the web or mobile applications without server-side programming so that development turns out to be quicker and easier.

What Can we do with FireBase?

With Firebase, we don’t have to stress over  servers or building REST APIs.

with this we just implement a little bit of configuration.we can also take every necessary step like ☟:

☑ Storing data.

☑ Verifying users

☑ Implementing access rules.

What technology does it support?

It supports:

  1. The web
  2. iOS
  3. OSX
  4. Android.

Benefits of FireBase Usage?

  1. No need to do server side coding.
  2. synced across connected devices in milliseconds, and available when your app goes offline.

Google Cloud Messaging:

  •  Google Cloud Messaging (commonly referred to as GCM) is a mobile notification service developed by Google that supports third-party application developers to send notification message from developer-run servers to applications that target the Google Android Operating System, as well as applications/extension developed for the Google Chrome internet browser.
  •  It is offered to developers free of charge.
  • It has been superseded by Google’s Firebase Cloud Messaging (FCM).

Firebase Cloud Messaging:

In this, we basically send push messages and receive them as notification. It is basically new version of cloud messaging now let’s discuss how it works:
Fire base push notification consists of two major processes

  1. Involvement of client registration.
  2. Broadcasting of the message from the FCM to all users.

 


Process:

  • The user sends a request to firebase for registration.

fcm-icodeslab-01

 

  • The Firebase will response in a string containing the unique token that will be generated for the particular user.

fcm-icodeslab-02

  • The token we obtain have to save somewhere so we need a remote server that has installed data base our remote server accepts the token and saves it into the data base.

fcm-icodeslab-03


Tutorial:

Getting Started With FireBase:

1.   Create a Project:

fcm-icodeslab-04

  • Create new project. For creating a new project, you have to set the country name and project name.

fcm-icodeslab-05

  • After that project will be created.
  • Select “Add Firebase to your Android App”.

fcm-icodeslab-06

  • A new popup will appear. We must provide a package name so go to your android studio app copy your package name and type it.

fcm-icodeslab-07

fcm-icodeslab-08

 


2.   Adding Google-service file to Project:

☛ Click on “ADD App” button in order to create “google-services.json” file.

  • You will get a popup to save “google-services.json”.
  • ADD “google-services.json” file in app file of your project.

fcm-icodeslab-09

  • By that, Google services which are a plugin for Gradle will load the google-services.json file that you just downloaded.

3.   Adding Dependencies:

  • Here, it says that we need to add some dependencies to our project so copy the selected portion and paste it in the version of build.gradle settings file.

 

fcm-icodeslab-10

fcm-icodeslab-11

fcm-icodeslab-12

 

  • Now Copy the second portion from Add Firebase to your app code.

fcm-icodeslab-13

  • paste it into the build.gradle (Module:app) apps version.

fcm-icodeslab-14

fcm-icodeslab-15

  •   Also add this ☟ dependency to your build.gradle (Module:app) apps version:
  •  compile com.google.firebase:firebase-messaging:9.8.0


fcm-icodeslab-16

  • Add the dependency ☟ for the firebase SDKs you want to use. I recommended starting with
  • compile ‘com.google.firebase:firebase-core:9.8.0’

fcm-icodeslab-17

  • After that press on the upper left Sync Now option after that press FINISH button.
  • We need to add service used to receive device token.
  • For that, we have to make class
  • In Android  -> app -> java -> 1stfolder of
    your package right clicks on.
  • New -> javaclass
  • After that type class name:  FirebaseInstanceIDService and do code:

 4.  Code For FireBase Instance ID Service:

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

/**

* Created by Habaiba Abbasi on 09/11/2016.

*/

//for background notifications

//it receives the token from firebase when the device id registered
public class FirebaseInstanceIDService extends FirebaseInstanceIdService {

        private static final String registed_Token="registed_Token";

  @Override
public void onTokenRefresh() {
   String  recent_token= FirebaseInstanceId.getInstance().getToken();

// get token from the server
Log.d(registed_Token,recent_token); // show device token in Log cat View
/* If you want to send messages to this application instance or

succeed this application contributions on the server side, send the

Instance ID token to your app server.

*/

sendRegistrationToServer(recent_token);

}

// this method is used to send token to your app server.

private void sendRegistrationToServer(String token) {

}

}


5.  Type Code For Message Service:

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

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

/**
 * Created by Habaiba Abbasi on 09/11/2016.
 */
public class MessageService extends FirebaseMessagingService {
     @Override      //this method is called when we received the message from Fcm
     public void onMessageReceived(RemoteMessage remoteMessage) {  //used for notifying the user in the form of notification
         Intent intent=new Intent(this,MainActivity.class);
         intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         PendingIntent pi = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
         NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this);
         // set notification properties
         notificationBuilder.setContentTitle("FCM Test"); //title of notification
         notificationBuilder.setContentText(remoteMessage.getNotification().getBody()); //in this method we pass extracted message to get actual message we pass parameter remotemessage which contain actual data.
          // tgetData returns the datatype of object that saves information in key value
         //to get value from our message we call method get with the key being message
         notificationBuilder.setAutoCancel(true);
         notificationBuilder.setSmallIcon(R.mipmap.ic_launcher); // change notification icon
         notificationBuilder.setContentIntent(pi);
         NotificationManager manager =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
         manager.notify(0,notificationBuilder.build());
 
 
     }

6.   Edit your AndroidManifest.xml file:

☛ Add this line

<uses-permission android:name=“android.permission.INTERNET”></uses-permission>

fcm-icodeslab-21

  • From top task-bar click on build .From
  • From the drop down menu select  Build APK.

fcm-icodeslab-22

  • Now, open a browser and select Firebase and move to console select your application and  click on manage.

 

 

fcm-icodeslab-18

  • On left side select notification from the menu.
  • Select new text and in message text type your message selects your delivery data and message label(optional) in target select user segment  after that select your package name.

☞ click on send a message.

 

fcm-icodeslab-23


 Final Output:

Congratulations!!! you received your notification.

fcm-icodeslab-24

Download Code

BY HABIBA ABBASI

2 thoughts on “Android Push Notifications using Firebase Cloud Messaging FCM

  1. Dear HABIBA ABBASI,
    Good tutorial thanks for your tutorial, its really helpful for new guys whom all looking for push notificastion.
    I have one doubt on integrating push notification in my project which is “Can you tell me how to navigate to specific activity when click on notification. Default it’s open app. But I need to know how to open an specific activity. ”

    Let me know. Thanks in advance.

    1. Hi Viswanath Thanks!

      In Message service class replace MainActivity.class with your specific activity you want to open in below intent .
      Intent intent=new Intent(this,MainActivity.class);

Leave a Reply

Your email address will not be published. Required fields are marked *