Following is a code sample for using GCM.
Client is android application.
Server is based on ASP.Net.
The sample is very naive and hard code is used:
- The android app is invoked , GCMRegister performs registration if needed and regId is saved and used on the server as strDeviceRegistrationId
- The ASP.Net is invoked, it use strDeviceRegistrationId and GoogleApiKey , to send a message to this particular device
- The android device "catch" this message via GCMBaseIntentService.onMessage
Client registration
GCMRegister
Important methods :
- register
- unregister
- getRegistrationId
This code register for GCM and the device registration ID is retrived - regId
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, Constants.SENDER_ID);
} else {
Log.v("TAG", "Already registered");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
GCMBaseIntentService
Important methods :
- onError
- onMessage
- onRegistered
- onUnregistered
Most important method is onMessage. the message is read via intent.getStringExtra("message");
public class GCMIntentService extends GCMBaseIntentService{
@Override
protected void onError(Context arg0, String arg1) {
//Called on registration or unregistration error.
Log.v("TAG", "GCMIntentService onError");
}
@Override
protected void onMessage(Context arg0, Intent intent) {
// TODO Auto-generated method stub
// --- Called when a cloud message has been received.
// --- handle here the push notification e.g. Toast Notification
Log.v("TAG", "GCMIntentService onMessage");
String message = intent.getStringExtra("message");
}
@Override
protected void onRegistered(Context arg0, String arg1) {
// TODO Auto-generated method stub
// --- Called after a device has been registered.
Log.v("TAG", "GCMIntentService Registered");
}
@Override
protected void onUnregistered(Context arg0, String arg1) {
// TODO Auto-generated method stub
// Called after a device has been unregistered.
Log.v("TAG", "GCMIntentService UnRegistered");
}
}
ASP.Net Server
The server uses :
- strDeviceRegistrationId which was registerd by the android
- GoogleApiKey which was retrive via Google APIs Console page->API Access->API key
- SenderId which was retrived via Google APIs Console page->Overview->Project Number
PushNotification.cs
public class AndroidGCMPushNotification
{
public string SendNotification(string deviceId, string message)
{
var value = message;
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
// --- text
tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
+ value + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + deviceId + "";
tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleApiKey));
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}
public string GoogleApiKey
{
get { return m_strGoogleAppID; }
set { m_strGoogleAppID = value; }
}
public string SenderId
{
get { return m_strSenderId; }
set { m_strSenderId = value; }
}
string m_strSenderId;
string m_strGoogleAppID;
}
first.aspx
<%@ Page Language="C#" %>
Sources :
- http://android.amolgupta.in/2012/07/google-cloud-messaging-gcm-tutorial.html
- http://www.codeproject.com/Tips/434338/Android-GCM-Push-Notification
Nathan