. f Android Firebase | Android Push Notifications using Firebase Cloud Messaging FCM ~ Android Developers Blog

Thursday, 23 November 2017

Android Firebase | Android Push Notifications using Firebase Cloud Messaging FCM

Hello Friends,
               Google moved from Google Cloud Messaging (GCM) to Firebase Cloud Messaging (FCM). Just like GCM, FCM is a cross-platform messaging solution that allows you to send messages. FCM is completely free and there are no limitations.

  • Firebase Message types : Using FCM you can send three types of messages i.e:
    • Notification Message
    • Data Message
    • both Notification & Data Payload


  • Integrating Firebase Cloud Messaging 
    • First thing you need to do is go to https://firebase.google.com/ and make an account to gain access to their console. After you gain access to the console you can start by creating your first project.
    • Give the package name of your project in which you are going to integrate the Firebase. Here the google-services.json file will be downloaded when you press add app button.


     



1. MainActivity.java
  1. package android.developer.solutions.firebasenotification.activity;  
  2.   
  3. import android.content.BroadcastReceiver;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.content.IntentFilter;  
  7. import android.content.SharedPreferences;  
  8. import android.developer.solutions.firebasenotification.R;  
  9. import android.developer.solutions.firebasenotification.app.Config;  
  10. import android.developer.solutions.firebasenotification.util.NotificationUtils;  
  11. import android.os.Bundle;  
  12. import android.support.v4.content.LocalBroadcastManager;  
  13. import android.support.v7.app.AppCompatActivity;  
  14. import android.text.TextUtils;  
  15. import android.util.Log;  
  16. import android.widget.TextView;  
  17. import android.widget.Toast;  
  18.   
  19. import com.google.firebase.messaging.FirebaseMessaging;  
  20.   
  21. public class MainActivity extends AppCompatActivity {  
  22.   
  23.     private static final String TAG = MainActivity.class.getSimpleName();  
  24.     private BroadcastReceiver mRegistrationBroadcastReceiver;  
  25.     private TextView txtRegId, txtMessage;  
  26.   
  27.     @Override  
  28.     protected void onCreate(Bundle savedInstanceState) {  
  29.         super.onCreate(savedInstanceState);  
  30.         setContentView(R.layout.activity_main);  
  31.   
  32.         txtRegId = (TextView) findViewById(R.id.txt_reg_id);  
  33.         txtMessage = (TextView) findViewById(R.id.txt_push_message);  
  34.   
  35.         mRegistrationBroadcastReceiver = new BroadcastReceiver() {  
  36.             @Override  
  37.             public void onReceive(Context context, Intent intent) {  
  38.   
  39.                 // checking for type intent filter  
  40.                 if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {  
  41.                     // gcm successfully registered  
  42.                     // now subscribe to global` topic to receive app wide notifications  
  43.                     FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL);  
  44.   
  45.                     displayFirebaseRegId();  
  46.   
  47.                 } else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {  
  48.                     // new push notification is received  
  49.   
  50.                     String message = intent.getStringExtra("message");  
  51.                     Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();  
  52.                     txtMessage.setText(message);  
  53.                 }  
  54.             }  
  55.         };  
  56.   
  57.         displayFirebaseRegId();  
  58.     }  
  59.   
  60.     // Fetches reg id from shared preferences  
  61.     // and displays on the screen  
  62.     private void displayFirebaseRegId() {  
  63.         SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);  
  64.         String regId = pref.getString("regId"null);  
  65.   
  66.         Log.e(TAG, "Firebase reg id: " + regId);  
  67.   
  68.         if (!TextUtils.isEmpty(regId))  
  69.             txtRegId.setText("Firebase Reg Id: " + regId);  
  70.         else  
  71.             txtRegId.setText("Firebase Reg Id is not received yet!");  
  72.     }  
  73.   
  74.     @Override  
  75.     protected void onResume() {  
  76.         super.onResume();  
  77.   
  78.         // register GCM registration complete receiver  
  79. //        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,  
  80. //                new IntentFilter(Config.REGISTRATION_COMPLETE));  
  81.   
  82.         // register new push message receiver  
  83.         // by doing this, the activity will be notified each time a new message arrives  
  84.         LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,  
  85.                 new IntentFilter(Config.PUSH_NOTIFICATION));  
  86.   
  87.         // clear the notification area when the app is opened  
  88.         NotificationUtils.clearNotifications(getApplicationContext());  
  89.     }  
  90.   
  91.     @Override  
  92.     protected void onPause() {  
  93.         LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);  
  94.         super.onPause();  
  95.     }  
  96. }  



2. MyFirebaseInstanceIDService.java

  1. package android.developer.solutions.firebasenotification.service;  
  2.   
  3. import android.content.Intent;  
  4. import android.content.SharedPreferences;  
  5. import android.developer.solutions.firebasenotification.app.Config;  
  6. import android.support.v4.content.LocalBroadcastManager;  
  7. import android.util.Log;  
  8.   
  9. import com.google.firebase.iid.FirebaseInstanceId;  
  10. import com.google.firebase.iid.FirebaseInstanceIdService;  
  11.   
  12.   
  13. /** 
  14.  * Created by Mukesh on 10/02/17. 
  15.  * www.androiddevelopersolutions.com/ 
  16.  */  
  17. public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {  
  18.     private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();  
  19.   
  20.     @Override  
  21.     public void onTokenRefresh() {  
  22.         super.onTokenRefresh();  
  23.         String refreshedToken = FirebaseInstanceId.getInstance().getToken();  
  24.   
  25.         // Saving reg id to shared preferences  
  26.         storeRegIdInPref(refreshedToken);  
  27.   
  28.         // sending reg id to your server  
  29.         sendRegistrationToServer(refreshedToken);  
  30.   
  31.         // Notify UI that registration has completed, so the progress indicator can be hidden.  
  32.         Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);  
  33.         registrationComplete.putExtra("token", refreshedToken);  
  34.         LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);  
  35.     }  
  36.   
  37.     private void sendRegistrationToServer(final String token) {  
  38.         // sending gcm token to server  
  39.         Log.e(TAG, "sendRegistrationToServer: " + token);  
  40.     }  
  41.   
  42.     private void storeRegIdInPref(String token) {  
  43.         SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);  
  44.         SharedPreferences.Editor editor = pref.edit();  
  45.         editor.putString("regId", token);  
  46.         editor.commit();  
  47.     }  
  48. }  


3. MyFirebaseMessagingService.java
  1. package android.developer.solutions.firebasenotification.service;  
  2.   
  3. import android.content.Context;  
  4. import android.content.Intent;  
  5. import android.developer.solutions.firebasenotification.activity.MainActivity;  
  6. import android.developer.solutions.firebasenotification.app.Config;  
  7. import android.developer.solutions.firebasenotification.util.NotificationUtils;  
  8. import android.support.v4.content.LocalBroadcastManager;  
  9. import android.text.TextUtils;  
  10. import android.util.Log;  
  11.   
  12. import com.google.firebase.messaging.FirebaseMessagingService;  
  13. import com.google.firebase.messaging.RemoteMessage;  
  14.   
  15. import org.json.JSONException;  
  16. import org.json.JSONObject;  
  17.   
  18.   
  19. /** 
  20.  * Created by Mukesh on 10/02/17. 
  21.  * www.androiddevelopersolutions.com/ 
  22.  */  
  23. public class MyFirebaseMessagingService extends FirebaseMessagingService {  
  24.   
  25.     private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();  
  26.   
  27.     private NotificationUtils notificationUtils;  
  28.   
  29.     @Override  
  30.     public void onMessageReceived(RemoteMessage remoteMessage) {  
  31.         Log.e(TAG, "From: " + remoteMessage.getFrom());  
  32.   
  33.         if (remoteMessage == null)  
  34.             return;  
  35.   
  36.         // Check if message contains a notification payload.  
  37.         if (remoteMessage.getNotification() != null) {  
  38.             Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());  
  39.             handleNotification(remoteMessage.getNotification().getBody());  
  40.         }  
  41.   
  42.         // Check if message contains a data payload.  
  43.         if (remoteMessage.getData().size() > 0) {  
  44.             Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());  
  45.   
  46.             try {  
  47.                 JSONObject json = new JSONObject(remoteMessage.getData().toString());  
  48.                 handleDataMessage(json);  
  49.             } catch (Exception e) {  
  50.                 Log.e(TAG, "Exception: " + e.getMessage());  
  51.             }  
  52.         }  
  53.     }  
  54.   
  55.     private void handleNotification(String message) {  
  56.         if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {  
  57.             // app is in foreground, broadcast the push message  
  58.             Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);  
  59.             pushNotification.putExtra("message", message);  
  60.             LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);  
  61.   
  62.             // play notification sound  
  63.             NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());  
  64.             notificationUtils.playNotificationSound();  
  65.         } else {  
  66.             // If the app is in background, firebase itself handles the notification  
  67.         }  
  68.     }  
  69.   
  70.     private void handleDataMessage(JSONObject json) {  
  71.         Log.e(TAG, "push json: " + json.toString());  
  72.   
  73.         try {  
  74.             JSONObject data = json.getJSONObject("data");  
  75.   
  76.             String title = data.getString("title");  
  77.             String message = data.getString("message");  
  78.             boolean isBackground = data.getBoolean("is_background");  
  79.             String imageUrl = data.getString("image");  
  80.             String timestamp = data.getString("timestamp");  
  81.             JSONObject payload = data.getJSONObject("payload");  
  82.   
  83.             Log.e(TAG, "title: " + title);  
  84.             Log.e(TAG, "message: " + message);  
  85.             Log.e(TAG, "isBackground: " + isBackground);  
  86.             Log.e(TAG, "payload: " + payload.toString());  
  87.             Log.e(TAG, "imageUrl: " + imageUrl);  
  88.             Log.e(TAG, "timestamp: " + timestamp);  
  89.   
  90.   
  91.             if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {  
  92.                 // app is in foreground, broadcast the push message  
  93.                 Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);  
  94.                 pushNotification.putExtra("message", message);  
  95.                 LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);  
  96.   
  97.                 // play notification sound  
  98.                 NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());  
  99.                 notificationUtils.playNotificationSound();  
  100.             } else {  
  101.                 // app is in background, show the notification in notification tray  
  102.                 Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);  
  103.                 resultIntent.putExtra("message", message);  
  104.   
  105.                 // check for image attachment  
  106.                 if (TextUtils.isEmpty(imageUrl)) {  
  107.                     showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);  
  108.                 } else {  
  109.                     // image is present, show notification with image  
  110.                     showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);  
  111.                 }  
  112.             }  
  113.         } catch (JSONException e) {  
  114.             Log.e(TAG, "Json Exception: " + e.getMessage());  
  115.         } catch (Exception e) {  
  116.             Log.e(TAG, "Exception: " + e.getMessage());  
  117.         }  
  118.     }  
  119.   
  120.     /** 
  121.      * Showing notification with text only 
  122.      */  
  123.     private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {  
  124.         notificationUtils = new NotificationUtils(context);  
  125.         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);  
  126.         notificationUtils.showNotificationMessage(title, message, timeStamp, intent);  
  127.     }  
  128.   
  129.     /** 
  130.      * Showing notification with text and image 
  131.      */  
  132.     private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {  
  133.         notificationUtils = new NotificationUtils(context);  
  134.         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);  
  135.         notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);  
  136.     }  
  137. }  


4. AndroidManifest.xml

  1. <manifest package="android.developer.solutions.firebasenotification" xmlns:android="http://schemas.android.com/apk/res/android">  
  2.   
  3.     <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsrtl="true" android:theme="@style/AppTheme">  
  4.         <activity android:label="@string/title_main_activity" android:name=".activity.MainActivity">  
  5.             <intent-filter>  
  6.                 <action android:name="android.intent.action.MAIN">  
  7.   
  8.                 <category android:name="android.intent.category.LAUNCHER">  
  9.             </category></action></intent-filter>  
  10.         </activity>  
  11.   
  12.         <!-- Firebase Notifications -->  
  13.         <service android:name=".service.MyFirebaseMessagingService">  
  14.             <intent-filter>  
  15.                 <action android:name="com.google.firebase.MESSAGING_EVENT">  
  16.             </action></intent-filter>  
  17.         </service>  
  18.   
  19.         <service android:name=".service.MyFirebaseInstanceIDService">  
  20.             <intent-filter>  
  21.                 <action android:name="com.google.firebase.INSTANCE_ID_EVENT">  
  22.             </action></intent-filter>  
  23.         </service>  
  24.         <!-- ./Firebase Notifications -->  
  25.     </application>  
  26.   
  27. </manifest>  


Download code from here

Hope you like this...
Enjoy Coding..... :)

Mukesh Kumar

Hi Guys I am from Delhi working as Web/Mobile Application Developer(Android Developer), also have knowledge of Roboelctric and Mockito ,android test driven development... Blogging has been my passion and I think blogging is one of the powerful medium to share knowledge and ideas....

0 comments:

Post a Comment

 

Copyright @ 2013 Android Developers Blog.