Firebase Cloud Messaging Service | Android

Today we are going to learn how you can send a notification from one Device to other Devices or a single Device with the help of Firebase Push Messaging Service.

So Lets Start:

  1. Create a Firebase Project and add your android application into it.
  2. Add these Dependencies in your app-level Gradle file:
    implementation 'com.android.volley:volley:1.1.0'
    implementation 'com.google.firebase:firebase-messaging:20.0.1'

3. let’s code our activity_main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Send Notification"
        android:onClick="notification"
        android:id="@+id/btn"
        android:layout_margin="20dp"/>


</RelativeLayout>

4. Now, let’s Code our MainActivity.java

public class MainActivity extends AppCompatActivity {

    private RequestQueue mRequestQue;
    private String URL = "https://fcm.googleapis.com/fcm/send";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


       
        Button send = findViewById(R.id.btn);
        mRequestQue = Volley.newRequestQueue(this);
        FirebaseMessaging.getInstance().subscribeToTopic("news");

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendNotification();
            }
        });

    }




    private void sendNotification() {

        JSONObject json = new JSONObject();
        try {
            json.put("to","/topics/"+"news");
            JSONObject notificationObj = new JSONObject();
            notificationObj.put("title","You have a new Message");
            notificationObj.put("body","Hi there I am texting you to test notification");
    
            json.put("notification",notificationObj);
            json.put("data",extraData);


            JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL,
                    json,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {

                            Log.d("Tac", "onResponse: ");
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("TAC", "onError: "+error.networkResponse);
                }
            }
            ){
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String,String> header = new HashMap<>();
                    header.put("content-type","application/json");
                    header.put("authorization","key=GET_YOUR_API_KEY_FROM_FIREBASE_CONSOLE");
                    return header;
                }
            };
            mRequestQue.add(request);
        }
        catch (JSONException e)

        {
            e.printStackTrace();
        }
    }
}

Now Let me explain to you what we did in MainActivity.java:

  1. First, we subscribed our user to a specific topic, for now, we are subscribing them to a topic called “news” by using FirebaseMessagingService:
        FirebaseMessaging.getInstance().subscribeToTopic("news");

2. then we created a method sendNotification that will be triggered whenever a user clicks on send button.

In this method, we created a JSON Object that contains details about our notification like to whom we want to send the notification what should be the title of the notification and what should be the notification description, after adding all the required information our JSON Object should be like this:

{"to" : "/topics/"+"YOUR_NOTIFICATION TOPIC",
"notification" : {"title" : "Your notification title",
                  "body: : "Your notification Description" }
}

Tip: For sending a notification to a specific single user, you can set the topic to receiving user’s userId and subscribe every user to his own userID in firebase messaging service.

For sending notification to a single User the code will look something like this:

        FirebaseMessaging.getInstance().subscribeToTopic("MyUserID");

notification JSON Object would be:
{"to" : "/topics/"+"reciever's User ID",
"notification" : {"title" : "Your notification title",
                  "body: : "Your notification Description" }
}

with these codes, you can send a notification to a single device or single user.

3. Now We will send a JSON request to Firebase Cloud Messaging API using Volley, In the request, we are going to add our JSON Object and will add our API keys in the parameters (Get your API keys from the firebase console):

RequestQueue requestQue;
requestQue = Volley.newRequestQueue(this);

String URL = "https://fcm.googleapis.com/fcm/send";

JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL,
                    json,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {

                            Log.d("Tac", "onResponse: ");
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("TAC", "onError: "+error.networkResponse);
                }
            }
            ){
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String,String> header = new HashMap<>();
                    header.put("content-type","application/json");
                    header.put("authorization","key=GET_YOUR_API_KEY_FROM_FIREBASE_CONSOLE");
                    return header;
                }
            };
            requestQue.add(request);

4. Just add these lines in your Manifest.xms and you are all set to send and receive notification:

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

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_launcher_background" />
        <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
             notification message. See README(https://goo.gl/6BKBk7) for more. -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />

        

That’s it Guys with these codes you can send notification from one device to another to learn more about Firebase notifications watch my Video Tutorial on Youtube where I will be teaching more complex features like Adding Extra Data with the notification, Opening Certain Activity on Notification Click and Sending Foreground Notifications: https://www.youtube.com/watch?v=OTomezM0ia8&list=PL2sOBQWr1QlOgTPmwEtQ3SASLEial0wZ8

3 thoughts on “Firebase Cloud Messaging Service | Android”

Leave a Reply

Your email address will not be published. Required fields are marked *