<h3><span id="What-is-Firebase-Cloud-Messaging" style="color: #000080;">What is Firebase Cloud Messaging?</span></h3>
<p>It is a service provided by Google. Google says “<strong><span style="color: #0000ff;">Firebase Cloud Messaging</span></strong> (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost.”</p>
<p>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.</p>
<p> ;</p>
<h4><span id="Message-Types" style="color: #000080;">Message Types</span></h4>
<p>Before moving ahead in the post let’s first understand the types of message that can be sent using FCM.</p>
<ol>
<li><strong><span style="color: #0000ff;">Notification Message:</span> </strong>Notification messages are handled by firebase SDK itself. Typically the notification message contains title, message, icon etc., These message can be sent from <strong><span style="color: #008000;"><a style="color: #008000;" href="https://console.firebase.google.com/" target="_blank" rel="nofollow noopener">firebase console</a> </span>UI. </strong>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.</li>
<li><span style="color: #0000ff;"><strong>Data message:</strong></span> 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.</li>
</ol>
<h3><span id="Adding-Firebase-Cloud-Messaging-to-Android-Project" style="color: #000080;">Adding Firebase Cloud Messaging to Android Project</span></h3>
<h4><span id="Creating-a-new-Android-Studio-Project" style="color: #0000ff;">Creating a new Android Studio Project</span></h4>
<ul>
<li>I have created a blank project using an Empty Activity, and I named it <span style="color: #008000;"><strong>FirebasePushNotificationExample</strong>.</span></li>
<li>So you have to do the same, you can change the project name to whatever you want.</li>
</ul>
<h4><span id="Adding-Firebase-Cloud-Messaging" style="color: #0000ff;">Adding Firebase Cloud Messaging</span></h4>
<ul>
<li>Click on tools and then select Firebase.</li>
</ul>
<p><img class="size-medium wp-image-464 aligncenter" src="https://c1ctech.com/wp-content/uploads/2018/06/select_firebase_ref-287x300.png" alt="" width="287" height="300" /></p>
<p> ;</p>
<ul>
<li>It will open an Assistant Window on the Right. From here you need to Select <strong><span style="color: #008000;">Cloud Messaging</span> </strong>(As shown in the image).</li>
</ul>
<p><img class="aligncenter wp-image-463 size-full" src="https://c1ctech.com/wp-content/uploads/2018/06/select_fcm_ref.png" alt="" width="598" height="716" /></p>
<p> ;</p>
<ul>
<li>Here you need to do two things.</li>
</ul>
<p><span style="color: #0000ff;"><strong><span id="Connect-to-Firebase">Connect to Firebase</span></strong></span></p>
<ul>
<li>Click on the first Button, <span style="color: #008000;"><strong>Connect to Firebase</strong>.</span></li>
</ul>
<p><img class="aligncenter wp-image-465 size-full" src="https://c1ctech.com/wp-content/uploads/2018/06/Capture103.png" alt="" width="601" height="314" /></p>
<p> ;</p>
<ul>
<li>It will open a new Window.</li>
</ul>
<p><img class="wp-image-466 size-full aligncenter" src="https://c1ctech.com/wp-content/uploads/2018/06/Capture104.png" alt="" width="794" height="659" /></p>
<p> ;</p>
<ul>
<li>From here you can create a new Firebase Project, or you can also select your existing project on firebase if any. Here we are building a new Firebase Project. Just put the name that you want for your project and click on <span style="color: #008000;"><strong>Connect to Firebase</strong>.</span></li>
<li>Now wait for a while, and you will see <span style="color: #008000;"><strong>Green Connected Message</strong>.</span></li>
</ul>
<p><img class="aligncenter wp-image-467 size-full" src="https://c1ctech.com/wp-content/uploads/2018/06/Capture101.png" alt="" width="597" height="316" /></p>
<p> ;</p>
<p><span style="color: #0000ff;"><strong><span id="Add-FCM-to-your-app">Add FCM to your app</span></strong></span></p>
<ul>
<li>Now click on the second button. Add FCM to your App. It will again open a new window, and here you need to accept the changes.</li>
</ul>
<p> ;</p>
<p><img class="aligncenter wp-image-468 size-full" src="https://c1ctech.com/wp-content/uploads/2018/06/Capture105.png" alt="" width="625" height="509" /></p>
<p> ;</p>
<ul>
<li>Then it will automatically do everything required for adding FCM to your application.</li>
</ul>
<p><img class="aligncenter wp-image-469 size-full" src="https://c1ctech.com/wp-content/uploads/2018/06/Capture102.png" alt="" width="605" height="413" /></p>
<h3><span id="Ways-of-Receiving-Push-Notification" style="color: #000080;">Ways of Receiving Push Notification</span></h3>
<p>Now first, we need to understand how we receive or send notifications using FCM. So there are two ways.</p>
<ol>
<li><strong><span style="color: #0000ff;">Using FCM Token:</span> </strong>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.</li>
<li><strong><span style="color: #0000ff;">Using Topic:</span> </strong>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.</li>
</ol>
<p><span style="color: #008000;"><strong><span style="color: #993366;">We can select from the above two methods to implement in our application. Here we will learn about the FCM Token</span> .</strong></span></p>
<h3><span id="Firebase-Cloud-Messaging-using-FCM-Access-Token" style="color: #000080;">Firebase Cloud Messaging using FCM Access Token</span></h3>
<p>In this method first, we will generate the access token. Now to get the access token, we create a class that extends <span style="color: #008000;"><strong>FirebaseInstanceIdService</strong>.</span> 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.</p>
<h4><span id="Generating-Access-Token" style="color: #0000ff;">Generating Access Token</span></h4>
<ul>
<li>Create a class named <span style="color: #008000;"><strong>MyFirebaseInstanceIdService</strong></span> in your project, and write the following code.</li>
</ul>
<p><span style="color: #0000ff;"><strong>MyFirebaseInstanceIdService.Java</strong></span></p>
<pre><code>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 {

 <span style="color: #008000;"><strong>//this method will be called
 //when the token is generated</strong></span>
 @Override
 public void onTokenRefresh() {

 <span style="color: #008000;"><strong>// Get updated InstanceID token.</strong></span>
 String refreshedToken = FirebaseInstanceId.getInstance().getToken();

 <span style="color: #008000;"><strong>//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</strong></span>

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


 }
}</code></pre>
<div id="crayon-5b19054a88959248495628" class="crayon-syntax crayon-theme-github crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" no-popup minimize scroll-mouseover">
<div class="crayon-toolbar" data-settings=" show">
<ul>
<li>As this class is a service, we need to define it in <span style="color: #008000;"><strong>AndroidManifest.xml</strong></span> as well.</li>
<li>So open your <span style="color: #008000;"><strong>AndroidManifest.xml</strong></span>file and just before the closing <span style="color: #008000;"><strong><;/application>;</strong></span> tag add the following code.</li>
</ul>
<pre><code><;service
 android:name=".MyFirebaseInstanceIdService">;
 <;intent-filter>;
 <;action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>;
 <;/intent-filter>;
<;/service>;</code></pre>
<h4><span id="Receiving-Messages" style="color: #0000ff;">Receiving Messages</span></h4>
<p>To receive the message we need to create a class that will extend <span style="color: #008000;"><strong>FirebaseMessagingService</strong></span>. Here we will override a method <strong><span style="color: #008000;">onMessageReceived</span>()</strong> that is called when we receive a message. Again this is also a service, so we need to define it in our <span style="color: #008000;"><strong>AndoirdManifest.xml</strong></span></p>
<!-- WP QUADS Content Ad Plugin v. 2.0.98.1 -->
<div class="quads-location quads-ad2" id="quads-ad2" style="float:none;margin:0px;">

</div>

<ul>
<li>Create a class named <span style="color: #008000;"><strong>MyFirebaseMessagingService</strong></span> and write the following code.</li>
</ul>
<p><span style="color: #0000ff;"><strong>MyFirebaseMessagingService.Java</strong></span></p>
<pre><code>package com.c1ctech.firebasepushnotificationexample;

import android.util.Log;

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

import static android.content.ContentValues.TAG;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

 @Override
 public void onMessageReceived(RemoteMessage remoteMessage) {
 super.onMessageReceived(remoteMessage);

 <strong><span style="color: #008000;">// Check if message contains a data payload.</span></strong>
 if (remoteMessage.getData().size() >; 0) {
 
 <strong><span style="color: #008000;">//handle the data message here</span></strong>
 Log.d(TAG, "Message data payload: " + remoteMessage.getData());


 <strong><span style="color: #008000;">//getting the title and the body</span></strong>
 String title = remoteMessage.getNotification().getTitle();
 String body = remoteMessage.getNotification().getBody();

 }
 }
}</code></pre>
<ul>
<li>Now again define it using the below XML code in your <strong><span style="color: #008000;">AndroidManifest.xml</span></strong> just before the closing tag <span style="color: #008000;"><strong><;/application</strong>>;.</span></li>
</ul>
<pre><code><;service
 android:name=".MyFirebaseMessagingService">;
 <;intent-filter>;
 <;action android:name="com.google.firebase.MESSAGING_EVENT"/>;
 <;/intent-filter>;
<;/service>;</code></pre>
<p> ;</p>
<div id="crayon-5b19054a88972495550349" class="crayon-syntax crayon-theme-github crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" no-popup minimize scroll-mouseover">
<div class="crayon-toolbar" data-settings=" show">
<h3><span id="Building-Push-Notification" style="color: #000080;">Building Push Notification</span></h3>
<p>Now let’s build the Push Notification. For this, I will use a Singleton class.</p>
<p><strong><span style="color: #993366;">Note: From Android Oreo, you need to create a notification channel or else notification will not be displayed.</span></strong></p>
<ul>
<li>So first we will define some constants for our Notification Channel in a separate class. Create a class named <strong><span style="color: #008000;">Constants</span></strong>. And write the following code</li>
</ul>
</div>
</div>
</div>
<p> ;</p>
</div>
<pre><code>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";
}</code></pre>
<ul>
<li>Now, create a class named <span style="color: #008000;"><strong>MyNotificationManager</strong> </span>and write the following code.</li>
</ul>
<p><span style="color: #0000ff;"><strong>MyNotificationManager.Java</strong></span></p>
<pre><code>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);


 <span style="color: #008000;"><strong>/*
 * 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
 * */</strong></span>

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

 <strong><span style="color: #008000;">/*
 * 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
 * */</span></strong>
 PendingIntent pendingIntent = PendingIntent.getActivity(mCtx, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

 <strong><span style="color: #008000;">/*
 * Setting the pending intent to notification builder
 * */</span></strong>

 mBuilder.setContentIntent(pendingIntent);

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

 <strong><span style="color: #008000;">/*
 * 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
 * */</span></strong>
 if (mNotifyMgr != null) {
 mNotifyMgr.notify(1, mBuilder.build());
 }
 }

}</code></pre>
<h3><span id="Testing-a-Local-Notification" style="color: #000080;">Testing a Local Notification</span></h3>
<p>Before moving ahead, we will confirm that the notification is working correctly. For this, we will create a local notification from the app itself.</p>
<ul>
<li>Come on <span style="color: #008000;"><strong>MainActivity.java</strong> </span>and write the following code.</li>
</ul>
<p> ;</p>
<pre><code>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);


 <strong><span style="color: #008000;">//If the device is having android oreo we will create a notification channel</span></strong>

 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);
 }

 <strong><span style="color: #008000;">//Displaying a notification locally</span></strong>
 MyNotificationManager.getInstance(getApplicationContext()).displayNotification("Hi","Where are you?");


 }
}
</code></pre>
<ul>
<li>Now try running your application.</li>
</ul>
<p> ;</p>
<p><img class="wp-image-477 size-full aligncenter" src="https://c1ctech.com/wp-content/uploads/2018/06/Screenshot_2018-06-09-16-41-441.png" alt="" width="480" height="800" /></p>
<p> ;</p>
<h3><span id="Testing-Notification-from-Firebase-Console" style="color: #000080;">Testing Notification from Firebase Console</span></h3>
<ul>
<li>Now let’s send a real notification from Firebase Console.</li>
<li>Open firebase console, then open your project that you are using. Then from the left menu click on <strong><span style="color: #008000;">grow ->; Cloud Messaging.</span> </strong></li>
</ul>
<p> ;</p>
<p><img class="aligncenter wp-image-470 size-full" src="https://c1ctech.com/wp-content/uploads/2018/06/sendmessage.png" alt="" width="1173" height="845" /></p>
<p> ;</p>
<ul>
<li>And after pressing the <span style="color: #008000;"><strong>Send Message</strong></span> button, you should see your message on the application.</li>
</ul>
<p> ;</p>
<p><img class="aligncenter wp-image-481 size-full" src="https://c1ctech.com/wp-content/uploads/2018/06/Screenshot_2018-06-08-17-53-081.png" alt="" width="480" height="800" /></p>
<p> ;</p>
<p> ;</p>
<p> ;</p>


