Implementing GCM in Android

By | April 2, 2018

Hi Friends,

In this article I will be talking about how you can implement GCM in Android using FirebaseMessaging Service.

Below are the steps you need to follow…

Create Project in Android Studio

Create a new project in Android Studio. The package name we use here will be used in the Firebase Console.

Create Project in Firebase Console

For GCM to work, we need to add our project in the Firebase Console. You will be asked to enter your package name which you can find in the AndroidManifest.xml file.

Download google-services

Eventually you can download the google-services.json file. Now copy this file in the project root directory.

Build Gradle

Add this in the project level build.gradle

buildscript {
   dependencies {
       compile 'com.google.firebase:firebase-messaging:10.2.1'
   }
}

AndroidManifest

Add Permissions

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

Add Firebase Services

We have to add the firebase services in the Manifest file.

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

Add Tags

Add this under the application tag

 	<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/ic_launcher" /> 
 	 <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/colorTransparent" /> 
 	 <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

 

Implementation – Java Code

Create a class named “MyFirebaseInstanceIDService” and copy these contents into it.
The class will be automatically called by the system and it will generate a Firebase Token which is the unique identifier for that particular device to which the messages will be sent to.

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import co.centroida.notifications.Constants;

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

private static final String TAG = "MyFirebaseIIDService";

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + 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.
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    preferences.edit().putString(Constants.FIREBASE_TOKEN, refreshedToken).apply();
    }
} 

Message Receiver

This class receives the message from Google Cloud. So when a message is sent to GCM it will be delivered to this class.

package read_sms.coderzheaven.com.readsms;

import android.content.Intent;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
import static read_sms.coderzheaven.com.readsms.Constants.IS_SERVER_APP;

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.i("GCM MessagingService", "GCM Message :: " + remoteMessage.getData());
        String title = remoteMessage.getData().get("title");
        // Show Notification here...
    }

}

Testing with Postman

If you have postman client, then you can test GCM instantly.

Go to postman and add the below URL

 	https://fcm.googleapis.com/fcm/send

Now add below two headers in Postman

Authorization : key=YOUR_FIREBASE_SERVER_KEY
Content-Type : application/json

For getting the Server Key, you need to go to the firebase console and check the ‘Cloud Messaging‘ tab.

Now in the Body Tab of your request in Postman, add these

{  
   "registration_ids":["DEVICE_FIREBASE_REG_TOKEN1", "DEVICE_FIREBASE_REG_TOKEN2"],
   "data":{  
      "title":"This is a sample data",
      "message":"This is a sample message",
      "image-url":"your_image_url"
   }
}

Note : Make sure you are supplying the correct REG TOKEN, otherwise the message will not be delivered, also each registration token will have some expiration date and
also you will get a new registration token when you reinstall the app.

Leave a Reply

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