Google Cloud Messaging (GCM) is a service that enables developers to send data from servers to both Android applications or Chrome apps and extensions. Wikipedia.
GCM basics involves four steps
Registering the client (Android Device)
Provide the registration ID to server
Send notifications from Server to GCM with registration ID
Receive notifications on the client
Prerequisite
Project Number (845696541232)
Server API Key (XIzaSyBDRJ00YJbTE011CbWWjlcKYUGI3eLccdI)
Once we have all the required data we can start with our client registration process.
Creating a new Project
Ensure that we have the necessary dependencies added.
app/build.gradle
Adding Permissions
app/src/main/Androidmanifest.xml
Registering the client (Android Device)
The client part has an interface with a registration button. On click of the button a call to GCM is made and Registration ID is obtained. While making the request it is necessary to note that we have the correct Project Number from the developers console.
res/layout/activity_main.xml
src/main/java/…/MainActivity.java
Declaring necessary variables and functions
Writing the registration function
Provide the registration ID to server
Once the registration is successful, Registration ID is obtained. This Registration ID is used by the server to send notifications to device. In our sample the Registration ID printed in logs is copied and used in the server part.
Send notifications from Server to GCM with Registration ID (Server Part)
The sample server code here is written in Nodejs. Using node-gcm library we can easily send messages to GCM. The server part includes two files.
package.json
node-gcm-sample.js
package.json
node-gcm-sample.js
Create both the files in a project folder, and execute npm install
Receive notifications on the client
Now we enter into the last part of preparing our client to receive notifications. We have to intimate the client to listen for notifications using a Receiver and a Service to handle the data from server.
src/main/java/…/GCMReceiver.java
Receiver code stating the necessary service (GCMIntentService) to be triggered.
Update Androidmanifest
app/src/main/Androidmanifest.xml
src/main/java/…/GCMReceiver.java
Service code for handling the notifications part. Here MESSAGE_KEY is the expected key that is set from the server.
Update Androidmanifest
app/src/main/Androidmanifest.xml
Now we are ready to check if our GCM component is working. Run the app in a device connected to internet, and open your server project folder from termial. Run node node-gcm-sample.js.Source code for Android Client and Node Server