Android Push Notifications using GCM (Google Cloud Messaging)

Introduction

Hi, this is my first post as a blogger, in this post I ‘ll show you how to send push notifications using GCM (Google Cloud messaging) from our HTTP server (or using curl, Postman or any Http Client).

This post shows the new method which is using google-services.json

Google provides GCM(Google Cloud Messaging) servers that allow sending downstream messages to registered Android devices and upstream messages from Device to Servers. In this post the focus will be only on the former part of sending downstream messages to Device from our server.

GCM Messages can have a maximum payload data of 4kb, enough to accommodate a Notification Title, the content and an image url and some other internal data that may be needed by the application for performing the required action like synchronizing the data like emails, product list, messages etc.

Let us have a look at the working Architecture:-

Let me clear a major misconception that GCM Messages are Notifications, but GCM Messages are the payload (usually JSON data) that is sent from the server to our Device (or multiple devices), the android device receives the JSON payload in real-time and the code implemented in Android Application may or may not display a notification based on the data received.

So let us get started implementing the Push Notifications in our app. In first step we will generate a Server API Key, for identifying our server backend , In second step we will generate a device token that will be used as an identity for our device for receiving messages.

Register the Application and Generate API Keys

We need to register our application and generate the google-services.json which will contain the API keys required.

Choose “Enable Services for my Android App” (in this case we are doing it for Android)

Give your application name in “App name” and the package name for our application in “Android package name”, in case you don’t know the package name, you can check it in your AndroidManifest.xml file in the first line in manifest tag) and click “Continue and configure services”

In this screen , you can choose the services which you want to add to enable for the application, Choose “Cloud messaging” as of now.

Okay, we are good with configuration now, Save the “Server API Key” and “Sender ID” at some place, we will need it later.

These 3 services will be implemented in next steps, lets discuss what they are for:-

RegisterationService:- Registers our device for the first time so that we can have a token for device identity, which will be used for sending the GCM messages/notification to this device.

MyInstanceIDListenerService:- Instance ID is the token for our device that was received during registering our device at GCM Server, if the token is refreshed due to any reason this service handles the device registration once again and updating the token on our backend server.

MyGcmListenerService:- This will be our interface to all the GCM messages being redirected to our app, We can either show notifications for these messages, process them in background or perform any database operations etc.

Lets get our hands on some Java code

1.Lets create the RegisterationService.Java that serves the simple purpose of registering our application and logs a the token against which the device is registered.

packagecom.wordpress.swarajsaaj.app.notificationdemo;importandroid.content.Intent;importandroid.os.Bundle;importandroid.support.v7.app.AppCompatActivity;importandroid.util.Log;/**
* Created by swarajpal on 06-03-2016.
*/publicclassMainActivityextendsAppCompatActivity{privatefinalStringTAG=this.getLocalClassName();@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);Log.d(TAG,&quot;Creatingtoken&quot;);Intentintent=newIntent(this,RegisterationService.class);startService(intent);}}

2.Create MyInstanceIDListenerService.java as discussed above.

packagecom.wordpress.swarajsaaj.app.notificationdemo;importandroid.content.Intent;importcom.google.android.gms.iid.InstanceIDListenerService;/**
* Created by swarajpal on 06-03-2016.
*/publicclassMyInstanceIDListenerServiceextendsInstanceIDListenerService{privatestaticfinalStringTAG=&quot;MyInstanceIDLS&quot;;/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. This call is initiated by the
* InstanceID provider.
*/@OverridepublicvoidonTokenRefresh(){// Fetch updated Instance ID token and notify our app's server of any changes (if applicable).Intentintent=newIntent(this,RegisterationService.class);startService(intent);}// [END refresh_token]}

The onTokenRefresh() method re registers the application using RegistertionService.java , you may optionally update the token on your server in this part.

3.Create the MyGcmListenerService.java for receiving the Push messages.

The onMessageReceived has two arguments String “from” and Bundle “data”, data contains the payload which is sent from the server.

sendNotification() method is a simple bare bones method for displaying notifications using NotificationManager.</li>
<li>Build and Launch the application using Phone or emulator, and lets test using POSTMAN which allows us making HTTP requests, or you can also send one using cURL using command line.Once you have run the application, the first thing it does is Register the device for a GCM token and Log it in console , here as shown.

Copy this token , which will be needed while sending the GCM message.Lets understand the JSON payload we are going to send to our device from server

{"data":{"title":"offer 3.","message":"Click to avail the offer."},"to":"<YOUR_DEVICE_TOKEN>"}

We have in Headers the
Authorization: key=<YOUR_SERVER_API_KEY>
which has our API_SERVER_KEY that we got in last section while registering our app.
Here “data” is the payload that will actually be transmitted to our device , we have two string in data json, the title and message that are handled in our MyGcmListenerService.java as shown in previous step.
The “to” field contains the token of the device we got after device registration, which denotes where the json payload will be sent to.

Now you can make the http request using your backend server if you already have one like:-