Enable Android Push Notification using Google Cloud Messaging (GCM)
Most likely, your app needs real time updates for dynamic content or for more user engagement. Earlier we used to have polling mechanism to refresh the data. Polling is too expensive to the system as it consume server and client resources even if there are no updates. To solve this we need push notification from server and here GCM (Google cloud messaging) help us.
Google Cloud Messaging is a free service from Google to send push notifications to device on demand.
Enabling GCM to your application:
There are two part of it. One is authentication of server and another is identification of device. We will go through step by step for each part.
1 . Server Authentication:
a ) Enable API : To get the server key go to Google developer console and select your project from top drop down menu. Once you select your project you can see your project details. Please note down your project number.
Click on the APIS & auth and select API . In mobile API, select “Cloud Messaging for Android” and enable the API.
b ) Create a Server Key : To create a server key go to credential section and in ADD CREDENTIAL Drop Down select 1st option Server key.
once you add server key you can see your server key listed in the API KEY section.
This is what we need to send push notification from server. While sending push notification via gcm server we need to send the device token and Server-Key in the request.
2. Device Identification :
Upon registering device with the GCM server, it will return registrationId. The GCM registrationId is an identifier to identify the mobile device. We need to store this on our server to send the push notification.
a) Register device with GCM server
First of all we need to add permission to your AndroidManifest.xml for GCM. Below two lines we need to add.
<uses-permission android:name="<YOUR APP PAKGE NAME>.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
b ) Add your notification receiver in AndroidManifest.xml file.
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.applozic.mobicomkit.sample" />
You can see applozic sdk sample code for reference.
c ) Getting RegistrationId.
Best thing is google play service provide convenient apis for gcm registration. Following is the two lines of code which is required to get the registrationId of device.
GoogleCloudMessaging gcm =GoogleCloudMessaging.getInstance(mActivity);
String regid = gcm.register(PROJECT_NUMBER);
Once we get the registrationId, send this registration-Id to your server. Server will use this device registration-Id while sending push notification to device.
You can find full code snippet from applozic android SDK on github.
Applozic is on a mission to bring real time communication to every connected application in a matter of few mins.
Want to bring real time communication capabilities to your apps?
Sign up now: Applozic