lockup.png

Firebase – Cloud Messaging

Introduction

  • Firebase Cloud Messaging, (formerly known as Google Cloud Messaging), is a new and improved way of delivering Push Notifications to major platforms that includes Android, iOS and web.

Why to switch over it?

Of Course, one should have reason to switch from GCM to FCM. Below are those:

  • You can send unlimited Upstream and Downstream Notifications

  • You can send messages to individual devices or a user segment

  • You can queue notifications

  • You can schedule notifications

  • And above all, it has improved battery performance tunings

Getting Started

Pre-requisites

  • Android Studio 1.5 or above

  • Google Play Services 9.0 or above

Add Firebase to your app

  1. Go to Firebase console and click on “CREATE NEW PROJECT”. Fill the “Project Name” and Select Country, then click on “CREATE PROJECT”

cropped1.png

  1. Click on “Add Firebase to your Android app”

cropped2.png

 

  1. Enter Package name and Debug signing certificate SHA-1(Optional) and click on “Add app” button

cropped3.png

  1. Google-services.json file will be downloaded. Go to Android Studio and Switch to the Project view in Android Studio to see your project root directory. Move the google-services.json file you just downloaded into your Android app module root directory.

cropped4.png

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

  2. Add the following lines, to your Project-level build.gradle (<project>/build.gradle):

buildscript {
dependencies {
// Add this line
classpath ‘com.google.gms:google-services:3.0.0’
}
}
  1. Add the following lines to the bottom of the file, to your App-level build.gradle (<project>/<app-module>/build.gradle):

// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'

  1. Add the following dependencies, to your App-level build.gradle

compile 'com.google.firebase:firebase-messaging:9.0.2'

  1. Finally, press “Sync now”

 

Code

  1. Register these services in your AndroidManifest.xml:

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

 

2. Create two files as below:

MyFirebaseInstanceIDService.java

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = “MyFirebaseIIDService”;

    @Override
    public void onTokenRefresh() {
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, “Refreshed token:”+refreshedToken);
        sendRegistrationToServer(refreshedToken);
    }

    private void sendRegistrationToServer(String token) {
        // save the token
    }
}

MyFirebaseMessagingService.java

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = “MyFirebaseMsgService”;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, “From:”+remoteMessage.getFrom());
        Log.d(TAG, “Notification Message Body:”+remoteMessage.getNotification().getBody());
        sendNotification(remoteMessage.getNotification().getBody());
    }

    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, intent,
                PendingIntent.FLAG_ONE_SHOT);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setContentTitle(“FCM Message”)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());
    }
}

 

3. By default, you have to call nothing. FCM calls its services by itself. Still if you want, you can call:

FirebaseInstanceId.getInstance().getToken();

Note: This method should be called in separate thread. AsyncTask is preferable.

 

That’s it…!!! By now, you are all ready to get notifications. Don’t forget to add internet permission in your AndroidManifest.xml:

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

Testing

  1. Go to Firebase Console. Go to your app and on left side menu, go to Notifications. If visiting this for the first time, click on “Send Your First Message”

cropped6.png

  1. Fill the message details and click on “Send Message”

cropped7.png

You should receive a notification in your device.

Important Points to remember

  • FCM token is generated even without invoking its services. So, it would be helpful if you write a method inside onTokenRefresh() that will save the token to SharedPreferences to use it later whenever you want.

  • To generate token, you can call: FirebaseInstanceId.getInstance().getToken();

  • To delete token, you can call: FirebaseInstanceId.getInstance().deleteInstanceId();

  • Note that, generating a token and deleting a token operations are blocking Main Thread (or UI Thread), so it’s preferable to encapsulate this code in AsyncTask

 

Conclusion

You see, integrating push notifications has become insanely easy. Hope you enjoyed learning FireBase Push Notifications.

Want to work with us? We're hiring!
  • Manish Patel

    Nice tutorial. Keep it up.(y) (y)

  • Parth Patel

    Awesome tutorial. simple & very easy!

  • Raghav Satyadev

    Sir, if i am writing FirebaseInstanceId.getInstance().getToken(); in an Intent Service, do I still have to get token in Asynctask ? as IntentService already runs in background and does allow to execute Asynctask directly from it.

    • As written it block main thread (i.e. UI thread) so he has mentioned you should call it using AsyncTask. But yes you can implement any background way for fetching/deleting token! Ultimately it should not block main thread.

      • Raghav Satyadev

        okay thank you sir.

  • Nishant Srivastava

    Very nicely written and easy to understand. +1