Google Cloud Messaging for Android

From June 26, 2012 C2DM has stopped accepting new users and request.

For using Push Notification on your android devices you can use GCM(Google Cloud Messaging) a new version of C2DM.

How to get Registered to GCM

1) To get registered to GCM goto
Google APIs Console page
and create a new project.

2) After creating project you can see the project id in the url.

Note down the project id as we require this id further, this id will be used as SENDER ID
in android project.

3) Click on Services on the left panel. Scroll down you will find Google Cloud Messaging for Android, turn it on. Accept all the terms and condition.

4.Click on API Access and note down the API Key. This API key will be used when sending requests to GCM server.

If you are done with above steps your registration for GCM is completed.

Implementing GCM in Android project

1) Create a new android project and fill the required details.

2) In AndroidManifest.xml file you have to add the following permissions:-

  • INTERNET – to use internet service.
  • WAKE_LOCK – required when you device sleeps.
  • ACCESS_NETWORK_STATE-used to access network state
  • GET_ACCOUNTS – google account required for GCM.
<permission android:name="com.projectname.permission.C2D_MESSAGE" android:protectionLevel="signature" />
 <uses-permission android:name="com.projectname.permission.C2D_MESSAGE" />>
 <!-- App receives GCM messages. -->
 <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
 <!-- GCM requires a Google account. -->
 <uses-permission android:name="android.permission.GET_ACCOUNTS" />
 <!-- Keeps the processor from sleeping when a message is received. -->
 <uses-permission android:name="android.permission.WAKE_LOCK" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>>
 <uses-permission android:name="android.permission.INTERNET"/>
 <application
 android:icon="@drawable/appln_icon"
 android:label="@string/app_name" >
 <uses-library android:name="com.google.android.maps" />
 <receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" >
 <intent-filter>
 <action android:name="com.google.android.c2dm.intent.RECEIVE" />
 <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
 <category android:name="com.projectname" />
 </intent-filter>
 </receiver>
 
 <service android:name=".GCMIntentService" />

3) Create a new class named NotificationDisplay.java and paste the following code. This class will show the notification that your device will receive.

package com.projectname;

import com.google.android.gcm.GCMRegistrar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class NotificationDisplay extends Activity implements OnClickListener
{
	String TAG = "GCM", notification_title, notification_msg, notification_type, notification_url;
	TextView title, message;
	Button okBtn;
	
	@Override
	protected void onNewIntent(android.content.Intent intent) 
	{
		Bundle extra= intent.getExtras();
		notification_title = extra.getString("TITLE");
		notification_msg = extra.getString("MSG");
		notification_type = extra.getString("TYPE");
		notification_url = extra.getString("URL");
		 onNotification();
		
	}
	
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notification_popup);
		Bundle extra= this.getIntent().getExtras();
		notification_title = extra.getString("TITLE");
		notification_msg = extra.getString("MSG");
		notification_type = extra.getString("TYPE");
		notification_url = extra.getString("URL");
		
		title = (TextView) findViewById(R.id.notification_titleTextID);
		message = (TextView) findViewById(R.id.notification_messageTextID);
		okBtn = (Button) findViewById(R.id.notification_okBtnID);
		
		okBtn.setOnClickListener(this);
		
		GCMRegistrar.checkDevice(this);
		
		// Make sure the device has the proper dependencies.
		 GCMRegistrar.checkDevice(this);
		 // Make sure the manifest was properly set - comment out this line
		 // while developing the app, then uncomment it when it's ready.
		 GCMRegistrar.checkManifest(this);
		 final String regId = GCMRegistrar.getRegistrationId(this);
		 
		 if (regId.equals("")) 
		 {
			 GCMRegistrar.register(this, Utils.GCMSenderId);
		 } else 
		 {
			 Log.e(TAG, "Already registered: "+regId);
		 }
		 
		 /**
		 We set this varible true when we recive notification
		  */
		 onNotification();
	}
		 
		 @Override
		 protected void onDestroy() 
		 {
			 try
			 {
				 super.onDestroy();
			 GCMRegistrar.onDestroy(this);
			 
			 }
			 catch (Exception e)
			 {
			 }
		 }
		 
		 public void onNotification()
                 {			 
		 title.setText(notification_title);
		 message.setText(notification_msg);
		 }

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(v == okBtn)
			{
				NotificationDisplay.this.finish();
			}
		}

	}

4) Create a class called Utils.java which contains the GCM information.

package com.projectname;

import android.app.Application;

public class Utils  extends Application
{
	public static String GCMSenderId = "278918080263";
	
	public static boolean notificationReceived;
	
        public static String notiTitle="",notiType="",notiMsg="",notiUrl="",registrationId = "";

}

5) Create a class called GCMIntentService.java

package com.projectname;
import java.util.Date;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.ViewDebug.FlagToString;
import com.google.android.gcm.GCMBaseIntentService;
import com.qrwinner.serverconnection.Constants;

public class GCMIntentService extends GCMBaseIntentService
{
	int t = (int)new Date().getTime();
	String TAG = "GCM";
	String notiTitle="",notiType="",notiMsg="",notiUrl="";

	public GCMIntentService() 
	{
		super(Utils.GCMSenderId);
	}
	@Override
	protected void onError(Context arg0, String regId) 
	{
		// TODO Auto-generated method stub
	}
	@Override
	protected void onMessage(Context arg0, Intent intent) 
	{
		// TODO Auto-generated method stub
		handleMessage(arg0, intent);
	}

	@Override
	protected void onRegistered(Context arg0, String regId) 
	{
		// TODO Auto-generated method stub
		 Utils.registrationId = regId;
	}

	@Override
	protected void onUnregistered(Context arg0, String arg1) 
	{
		// TODO Auto-generated method stub
	}
	
	private void handleMessage(Context context, Intent intent) 
	{
		 // TODO Auto-generated method stub
		 Bundle extra= intent.getExtras();
		 notiMsg = extra.getString("msg");
		 notiTitle = extra.getString("title");
		 notiType = extra.getString("type");
		 notiUrl = extra.getString("url");
		 
		 int icon = R.drawable.appln_icon; // icon from resources
		 CharSequence tickerText = notiTitle;//intent.getStringExtra("me"); // ticker-text
		 long when = System.currentTimeMillis(); // notification time
		 CharSequence contentTitle = ""+notiTitle; //intent.getStringExtra("me"); // message title
		
		 NotificationManager notificationManager =
		 (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		 
			 Notification notifyDetails = new Notification(icon,"Notification Alert",when);
		              
		      notifyDetails.defaults |= Notification.DEFAULT_SOUND;
		      notifyDetails.flags |= Notification.FLAG_AUTO_CANCEL;
		      notifyDetails.vibrate=new long[] {20L, 20L, 30L, 60L};
		      
			 Intent notificationIntent = new Intent(context, com.projectname.NotificationDisplay.class);
			 notificationIntent.putExtra("TITLE", notiTitle);
			 notificationIntent.putExtra("MSG", notiMsg);
			 notificationIntent.putExtra("TYPE", notiType);
			 notificationIntent.putExtra("URL", notiUrl);
			 PendingIntent pendingIntent = PendingIntent.getActivity(context, t, notificationIntent,PendingIntent.FLAG_ONE_SHOT);
			notifyDetails.setLatestEventInfo(context, contentTitle, notiMsg, pendingIntent);
			 notificationManager.notify(t, notifyDetails);
			Utils.notificationReceived=true;
			notifyDetails.defaults |= Notification.DEFAULT_SOUND;
			 notifyDetails.flags |= Notification.FLAG_AUTO_CANCEL;
		 }
}

6) You are almost done with the GCM push notification. You just have register your device to GCM, for that you have to call the following function “initGCM” in your “Splash” screen or the first activity of your project.

private void initGCM() 
	{
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);
		final String regId = GCMRegistrar.getRegistrationId(this);
		if (regId.equals("")) 
		{
		  GCMRegistrar.register(this, Utils.GCMSenderId);
		} else {
		}
		
	}

“regId” is your unique GCM register ID of your device.

NOTE:- GCM register ID is unique for all devices. Even you register several time. GCM will return the same register ID.

When you receive this “regId” send it to your server and set a cron to receive notification.