FCM
As everyone knows the importance of push notification in apps, we will discuss FCM (Firebase Cloud Messaging) in this article.
Let’s see what the definition of FCM is.
Firebase Cloud Messaging is a powerful API that lets you deliver the messages reliably and independently of the platform you are developing on. With the help of FCM, you can send notification and message to your client’s app. We can send instant messages of up to 4KB in size.
Before moving ahead, we will summarize how we are going to implement it.
- We are going to develop an Android app that will display the notification.
- Setting up FCM.
- Saving token ID generated from android device to server using web service developed in .net
- Sending notification message from C# code.
Android app to display a notification
- First, let us create a new Android Studio Project with an Empty Activity.
- Once your project is loaded, click on "Firebase" from the Tools menu. With Android Studio 2.2, it is really easy to integrate Firebase into your project.

- All the available features will get opened. Click "Cloud Messaging".

- Click on "Set up Firebase Cloud Messaging".

- Click on the "Connect to Firebase" button. A dialog will open.


- Enter the project name and click on "Connect to Firebase".
- Click on the button "Add FCM to your app" and you will see a dialog box.

- Click on "Accept Changes".
- Every device generates a unique token or device id to receive notifications. And for this, we have to create a class that will extend the class FirebaseInstanceIdService. So, we have created MyFirebaseInstanceIDService.java
- To store the generated token in SharedPreferences, we have created SharedPrefManager.java in Singleton Pattern.
- To actually receive the notification FirebaseMessagingService is used, so we will create MyFirebaseMessagingService.java.
- We will edit the activity_main.xml file.
- Also, we will edit the MainActivity.java file.
- Also, edit the AndroidManifest.xml file.
MyFirebaseInstanceIDService.java
- package com.infobytessolutions.sretailer;
- /**
- * Created by Nilesh on 05/12/2017.
- */
- 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";
- @Override
- public void onTokenRefresh() {
- //Getting registration token
- String refreshedToken = FirebaseInstanceId.getInstance().getToken();
- //Displaying token on logcat
- Log.d(TAG, "Refreshed token: " + refreshedToken);
- //calling the method store token and passing token
- storeToken(refreshedToken);
- }
- private void storeToken(String token) {
- //saving the token on shared preferences
- SharedPrefManager.getInstance(getApplicationContext()).saveDeviceToken(token);
- }
- }
SharedPrefManager.java
- package com.infobytessolutions.sretailer;
- /**
- * Created by Nilesh on 05/12/2017.
- */
- import android.content.Context;
- import android.content.SharedPreferences;
- public class SharedPrefManager {
- private static final String SHARED_PREF_NAME = "FCMSharedPref";
- private static final String TAG_TOKEN = "tagtoken";
- private static SharedPrefManager mInstance;
- private static Context mCtx;
- private SharedPrefManager(Context context) {
- mCtx = context;
- }
- public static synchronized SharedPrefManager getInstance(Context context) {
- if (mInstance == null) {
- mInstance = new SharedPrefManager(context);
- }
- return mInstance;
- }
- //this method will save the device token to shared preferences
- public boolean saveDeviceToken(String token){
- SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = sharedPreferences.edit();
- editor.putString(TAG_TOKEN, token);
- editor.apply();
- return true;
- }
- //this method will fetch the device token from shared preferences
- public String getDeviceToken(){
- SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
- return sharedPreferences.getString(TAG_TOKEN, null);
- }
- }
MyFirebaseMessagingService.java
- package com.infobytessolutions.sretailer;
- /**
- * Created by Nilesh on 05/12/2017.
- */
- 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;
- import org.json.JSONException;
- import org.json.JSONObject;
- public class MyFirebaseMessagingService extends FirebaseMessagingService {
- private static final String TAG = "MyFirebaseMsgService";
- @Override
- public void onMessageReceived(RemoteMessage remoteMessage) {
- if (remoteMessage.getData().size() > 0) {
- Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
- try {
- JSONObject json = new JSONObject(remoteMessage.getData().toString());
- // sendPushNotification(json);
- sendNotification(json);
- } catch (Exception e) {
- Log.e(TAG, "Exception: " + e.getMessage());
- }
- }
- }
- private void sendNotification(JSONObject json) {
- Intent intent = new Intent(this, MainActivity.class);
- intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- Log.e(TAG, "Notification JSON " + json.toString());
- try{
- JSONObject data = json.getJSONObject("data");
- String title = data.getString("title");
- String message = data.getString("message");
- String imageUrl = data.getString("image");
- 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_launcher_background)
- .setContentTitle(title)
- .setContentText(message)
- .setAutoCancel(true)
- .setSound(defaultSoundUri)
- .setContentIntent(pendingIntent);
- NotificationManager notificationManager =
- (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
- notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
- } catch (JSONException e) {
- Log.e(TAG, "Json Exception: " + e.getMessage());
- } catch (Exception e) {
- Log.e(TAG, "Exception: " + e.getMessage());
- }
- }
- }
activity_main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/activity_main"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- tools:context=".MainActivity">
- <EditText
- android:id="@+id/editTextPhoneNo"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_above="@+id/buttonRegister"
- android:hint="Enter Phone No"
- android:inputType="phone" />
- <Button
- android:layout_centerVertical="true"
- android:text="Register Device"
- android:id="@+id/buttonRegister"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- </RelativeLayout>
MainActivity.java







Aric CampebllPosted Jul 21, 2020, 9:05 PM
Can this work for data messages to the client without the push notification? Thanks
Manoj KumarPosted Feb 25, 2020, 7:20 AM
Very Nice Informative Article <a hre="https://www.computersciencejunction.in/2020/02/13/relational-algebra-in-dbms/">Relational Algebra in Dbms </a>
Edzio AuditorePosted Jun 19, 2018, 4:15 AM
Hi ' Nilesh ' , thank you for the tuto, i want to send notification from restful sevices webApi from asp.net app to my android app using FireBase, and this when i have for example in my database in sql Server some changes in some table ... any help appreciated thanks !!!