Android

Android Push Notification using Firebase Cloud Messaging.

Firebase Cloud Messaging

Firebase Cloud Messaging

Implement Android Push Notification using Firebase Cloud Messaging service

Hello Friends we all know about push notifications which inform us about something new service integrated in the app or some new features updated in the existing app.

Most common are Instagram follows, likes and recommendations and it goes the same way for all applications.

Google Cloud Messaging service which is deprecated now because of Google Play services 9.0 update.So now GCM is succeeded by FCM (Firebase Cloud Messaging).
So lets start now.

What is Firebase ?

Firebase is a powerful platform for building Android, iOS and web based applications. Firebase offers real time data storage and synchronization, user authentication, analytics, hosting, database, remote configuration, notification, cloud messaging and lots more. Before the Google I/O 2016, we used Google Cloud Messaging service (GCM) to send data: notification, messages from the server to the clients or android app users. Google introduced the Firebase cloud messaging in Google I/O 2016.

So here we will see the Android Push Notification demo using latest Firebase support.

Note:I assume that you have updated your Android sdk to the latest.

This tutorial will be divided into two parts :

1. Android Studio Project Setup.

2. Project creation on FCM console.

PART 1

Step 1: Create Android Studio Project called as FCM Demo and open its app level build.gradle and it should look like this:

It requires:

com.google.firebase:firebase-messaging:9.0.2


apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "com.askfortricks.fcmdemo"
minSdkVersion 14
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.google.firebase:firebase-messaging:9.0.2'
}
apply plugin: 'com.google.gms.google-services'

view raw

build.gradle

hosted with ❤ by GitHub

Step 2 :Now open your project level build.gradle and it should have these lines:

classpath com.google.gms:google-services:3.0.0


// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

view raw

build.gradle

hosted with ❤ by GitHub

Step 3:Now we need to include this MyFirebaseInstanceIDService which handles the process of fetching the FCM token from the server:

onTokenRefresh() method contains sendRegistrationToServer(refreshedToken)

and storeTokenToPreference(refreshedToken) methods which do what their name suggest.

Here storeTokenToPreference(refreshedToken) method stores the token once it arrives into Shared Preference (which you need to create) and makes it available throughout the app.

And sendRegistrationToServer() method will send that token to your web service for further processing as per your needs.


package com.askfortricks.fcmdemo;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the InstanceID token
* is initially generated so this is where you would retrieve the token.
*/
// [START refresh_token]
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(refreshedToken);
/**
*Also you can store the token in preference for your later use in the app,
*Because you have already fetched it on launching activity.
*/
storeTokenToPreference(refreshedToken);
}
private void storeTokenToPreference(String refreshedToken) {
}
// [END refresh_token]
/**
* Persist token to third-party servers.
*
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* maintained by your application.
*
* @param token The new token.
*/
private void sendRegistrationToServer(String token) {
// Add custom implementation, as needed.
}
}

Step 4 : Now this class creates notification when FCM message is received on the mobile phone.We will send test FCM message from Notification section of FCM console later on:


package com.askfortricks.fcmdemo;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
}
// [END receive_message]
/**
* Create and show a simple notification containing the received FCM message.
*
* @param messageBody FCM message body received.
*/
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle("My FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}

Step 5 : Main Activity file which prints the FCM token in the Logcat:


package com.askfortricks.fcmdemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.firebase.iid.FirebaseInstanceId;
public class MainActivity extends AppCompatActivity {
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//here we have to check whether the device on which
//app is running had the Play services available or not.
if(checkPlayServices())
{
printMyFCMToken();
}
//If you click on button your FCM will be printed in Log
Button btnPrintFCMToken=(Button)findViewById(R.id.btnPrintFCMToken);
btnPrintFCMToken.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
printMyFCMToken();
}
});
}
private void printMyFCMToken()
{
Log.e("FCM Token=",""+ FirebaseInstanceId.getInstance().getToken());
}
private boolean checkPlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
}
return false;
}
return true;
}
}

Part 2: Firebase Console part

Step 6: Open https://firebase.google.com/ and click on Go to console at right side and you will see below screen:

firebase_console_home
firebase_console_home

Step 7: After selecting Create New Project below screen will appear, Fill the details as I have filled according to my demo project and click Create Project:

create_project

Step 8: As your project will be created ,you will see the new page which displays your Project name at the extreme left (FCM Demo) in my case, now click Add firebase to your Android app:

add_firebase

Step 9: Below screen will open and fill the package name and SHA1 and click Add App. To get these details follow step 10:

sha1hide

Step 10(Ten): Fetch SHA-1 from Android Studio:

stepsfor_sha1

Step 11: As you complete Add App in step 9 ,automatically google-services.json file will be downloaded with this screen visible to you, copy the google-services.json file to your app directory,as shown in the image below:

copy_json

Step 12: On Click of Continue ,you will be shown console home screen. Click on Send Your First message:

notification

Step 13: Completed the copying google-services.json file ,run the FCM demo app on your mobile, and copy the FCM token.

Step 14:  Paste the FCM token that you have copied from the log in Android Studio, select Single device and click SEND MESSAGE button.

last_stepnotification

Step 15:  check your mobile and you will receive notification like below:

mob

If you have any doubts or suggestions please comment . I will be glad to improve by your suggestions.

You can get the full source code from here:

Remember to include your own google-services.json file to run this demo.

https://github.com/developerhuman12/FCMDemo

Top 10 free Android libraries for app development in android studio

Feeling glad to receive your comment