FireBase push notification android

Google announced the new strong product Firebase in Google I/O 2016 . Firebase is a cloud platform with some of amazing feature for android development. Firebase cloud messaging (FCM) is free messaging service from Google that not required any server side code. Earlier google has provided GCM that is Google cloud messaging for push notification which was required server side code to execute the push message. FCM is the new version of GCM.

These are the differences between these two services:

Firebase Cloud Messaging provides a complete set of messaging capabilities through its client SDKs and HTTP and XMPP server protocols. For deployments with more complex messaging requirements, FCM is the right choice.

Firebase Notifications is a lightweight, serverless messaging solution built on Firebase Cloud Messaging. With a user-friendly graphical console and reduced coding requirements, Firebase Notifications lets users easily send messages to reengage and retain users, foster app growth, and support marketing campaigns. If you want a more detailed comparison. Read this.

Lets see the basic configuration

To integrate the Firebase push notification in android we need to follow few steps .

Step.1: Please go to Firebase console to create the project



Step.2: Now you can create the project name and enter your county name. Please refer the below snap.



Step.3: You have to choose which platform do you want to use firebase push. Here we are configuring for android platform, so I am choosing option for android app.



Step.4: Now you need to enter your package name of your project. Ex: Here my package name is "com.sunil.firebasepushnotificationandroid" . Other fields are optional for debug mode. But if you want to release your app that time you need to pass the SHA-1 key.



Step.5: Once you done your step.5 You will get downloded one google-services.json file. You have to copy this file and paste inside the app folder. Please see the below snap to get thing done.



Step.6: Add these dependencies to your build.gradle file.



Wow! you have done the configuration steps completely. Lets focus on code required for push in client side. Firebase push is required two service, one for get the token or registration Id and other for listen the push message to notify to particular device. Here are the details of services.

MyFirebaseInstanceIDService.java

import android.content.SharedPreferences;
import android.util.Log;
 
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import com.sunil.firebasepushnotificationandroid.MainApplication;
import com.sunil.firebasepushnotificationandroid.config.Config;
import com.sunil.firebasepushnotificationandroid.contstant.Constant;
 
/**
 * Created by sunil on 21-Oct-16.
 */
 
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
 
    private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();
 
    /**
     * 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.
     */
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);
 
        // Saving reg id to shared preferences
        storeRegIdInPref(refreshedToken);
 
        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        sendRegistrationToServer(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) {
        // TODO: Implement this method to send token to your app server.
        // this is required to send this registration Id to your server if you want push message from server side.
    }
 
    private void storeRegIdInPref(String token) {
        SharedPreferences pref = MainApplication.getInstance().getSharedPreferences(Config.SHARED_PREF, 0);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString(Constant.REGISTRATION_ID, token);
        editor.commit();
    }
}


MyFirebaseMessagingService.java

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.batch.android.json.JSONObject;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.sunil.firebasepushnotificationandroid.MainActivity;
import com.sunil.firebasepushnotificationandroid.R;
 
/**
 * Created by sunil on 21-Oct-16.
 */
 
public class MyFirebaseMessagingService extends FirebaseMessagingService {
 
    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
 
    /**
     * 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) {
 
        if (remoteMessage == null)
            return;
 
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }
 
        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            sendNotification(remoteMessage.getNotification().getBody());
        }
 
        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
            try {
                JSONObject json = new JSONObject(remoteMessage.getData().toString());
                // parse json and get the string to show in notification.
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
 
    }
    // [END receive_message]
 
    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)
                .setSmallIcon(R.drawable.message)
                .setContentTitle("FCM Message")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);
 
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 
        notificationManager.notify(0 , notificationBuilder.build());
    }
}


AndroidManifest.xml

<manifest package="com.sunil.firebasepushnotificationandroid" xmlns:android="http://schemas.android.com/apk/res/android">
 
    <uses-permission android:name="android.permission.INTERNET"/>
 
    <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:name=".MainApplication" android:supportsrtl="true" android:theme="@style/AppTheme">
            <intent-filter>
               <action android:name="android.intent.action.MAIN"/>
 
                <category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
       </activity>
 
    
    <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>
    
 </application>
</manifest>


These basic code is required for push. Firebase aslo handle itself when the device is in background. It will notify user with push message. Firebase also provide feature for developer to send custom message like title, image, url link etc in json fomate. Developer needs to parse them before notify.

Now here I am not using server side push. So I will push from Firebase console panel.



If you selected push message Send Now. It will push the message to registered devices.



I hope it will help to all newbie developer to implement push notification by using Firebase.

Thanks for your valuable time to reading this post.

6 comments:

  1. This blog is really annoying because of ads.. everywhere.

    ReplyDelete
    Replies
    1. Thanks, I will remove annoying ads. Thanks for ur suggestion.

      Delete
  2. Nice tutorial... but where can I download the source code ?

    ReplyDelete
    Replies
    1. Hi, Thanks for appreciate. I will add download link soon.

      Delete
  3. how to get data value firebase when app ini background or kill???...

    ReplyDelete
    Replies
    1. Firebase itself handling push data when app in background.

      Delete

Debug Database in Android

In my last tutorial, we have learned how we can use persistence database in android. We also understood which database wrapper we can use...

Contact Me

Name

Email *

Message *