First of all what is this Google Cloud Messaging or simply
GCM?
*As for the Google introduction “Send data from
your server to your users' devices, and receive messages from devices on the
same connection. The GCM service handles all aspects of queuing of messages and
delivery to client applications running on target devices, and it is completely
free.”
Derived from above phase GCM is a free, server based messaging service which can be used for either sending downstream messages such as
“push notifications” or sending and receiving messages which can be implemented
as a simple chat application or whatever the need you have.
Before going on deep I should say that this
article is a bit technical for the newbies for android and server programming
but don’t get behind, once you learnt the basics, those things are not much
harder to learn.
How is it works?
There are 2 ways to use GCM,
1. Use only for downstream messages such as push notifications
2. Use for both upstream and downstream messages using GCM
connection server
Why GCM?
·
The main advantage of GCM over
other alternatives is its completely
free.
·
You don’t have to worry above
certain things such as queuing, late delivery, GCM will take care of all
these.
·
GCM supports up to 4KB payload so
you can send more data.
·
GCM is easy to implement so you
don’t need to do much coding.
GCM for
Downstream messages
Here we can only send downstream messages to a device,
this kind of implementations are widely used in “push notification sending
systems”.
Before doing anything dramatic we need to setup our android
studio project to use with GCM.
Here are the steps you need to follow to setup your project
correctly
1. Set up
Google play services
2. Edit
your Application’s manifest
Above steps are explained in detail here
If you have done all the things correctly
as I mentioned above, you have successfully configured your project.
Then to communicate with GCM server you
have to obtain an “InstanceID” token. this InstanceID token will uniquely
identify the device. This is kind of registering your devices in GCM database.
InstanceID instanceID = InstanceID.getInstance(this);
String token =instanceID.getToken(Google Project ID,
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
String token =instanceID.getToken(Google Project ID,
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Here Google Project
ID is a unique identifier you get when you created a project in Google
Application console.
Getting an InstanceID might block
your UI thread so make sure you do it in a Separate thread.
Save above token in a persistence
manner to use again.
You have completed the basic steps,
so the device configuration is done. Now you have to make a server to connect
your device with GCM server.
I’m not going to cover the all aspects
of creating the server. You can find all those details in their developer
guide.
You can create the server using HTTP
or XMPP but just remember that HTTP one is only working with downstream messages,
if you need to implement upstream messages as well, you have to go with the
XMPP server which is my personal favor as well.
Assuming that the server
implementation is complete now you have to create a way to catch the messages
which are being send from the server.to achieve that we can use below code.
To
receive simple downstream messages, use a Service that extends
GcmListenerService
to handle messages
captured by GcmReceiver
. GcmReceiver
extends WakefulBroadcastReceiver
, guaranteeing that the CPU
is awake so that your listener service can complete its task.
By
overriding the method
GcmListenerService.onMessageReceived
, you can perform actions
based on the received message:
@Override
public void onMessageReceived(String from, Bundle data) { String message = data.getString("message"); Log.d(TAG, "From: " + from); Log.d(TAG, "Message: " + message); if (from.startsWith("/topics/")) { // message received from some topic. } else { // normal downstream message. } // ... }
After receiving the messages you can choose the action based on the message.
GCM for
Upstream and downstream messages
As I mentioned above we have
to use XMPP if we are going to implement bidirectional messaging.
You can find how to
implement the XMPP server here:
You have to repeat all the
steps we have done in downstream only method and need to do some new steps
also.
1. Create a method to send upstream messages
public void onClick(final View view) {
if (view == findViewById(R.id.send)) {
new AsyncTask() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
Bundle data = new Bundle();
data.putString("my_message", "Hello World");
data.putString("my_action","SAY_HELLO");
String id = Integer.toString(msgId.incrementAndGet());
gcm.send(Google Project ID + "@gcm.googleapis.com", id,data);
msg = "Sent message";
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
} else if (view == findViewById(R.id.clear)) {
mDisplay.setText("");
}
}
if (view == findViewById(R.id.send)) {
new AsyncTask() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
Bundle data = new Bundle();
data.putString("my_message", "Hello World");
data.putString("my_action","SAY_HELLO");
String id = Integer.toString(msgId.incrementAndGet());
gcm.send(Google Project ID + "@gcm.googleapis.com", id,data);
msg = "Sent message";
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
} else if (view == findViewById(R.id.clear)) {
mDisplay.setText("");
}
}
make sure to do above code
in a separate thread.
Here “send” method in “
GoogleCloudMessaging
” object will responsible to send
the message.
The objective of this post is to give you
an introduction about what is GCM and how it works.to learn more about this you
can follow their official developer guide.
I can’t cover all the steps in detail here
in this post because this one is just an Introduction but I’ll make another
post about how we can actually implement this using relevant code. Until then
Happy Coding.
Chathuranga Sandaruwan
0 comments :