Thursday 21 November 2013

Android push notification

Push Notification for Android using GCM



C2DM was launched in 2010 to help Android apps send data from servers to their applications. Servers can tell apps to contact the server directly, to fetch updated application or user data. The C2DM service handles all aspects of queueing of messages and delivery to the target application running on the target device.


GCM is Google’s new Cloud Messaging System, that has replaced C2DM.


Google Cloud Messaging for Android (GCM) is a service that allows you to send data from your server to your users' Android-powered device, and also to receive messages from devices on the same connection. The GCM service handles all aspects of queueing of messages and delivery to the target Android application running on the target device. GCM is completely free no matter how big your messaging needs are, and there are no quotas.


You can go through the official documentation if you want to know more about GCM.


Please follow the below steps to implement Push Notification in Android :


Creating Google API Project :


To create a Google API project:
  1. If you haven't created an API project yet, this page will prompt you to do so:



  1. Click Create project. Your browser URL will change to something like:
https://code.google.com/apis/console/#project:4815162342
  1. Take note of the value after #project: (4815162342 in this example). This is your project number, and it will be used later on as the GCM SENDER_ID.



Enabling GCM service :


  1. In the main Google APIs Console page, select Services.
  2. Turn the Google Cloud Messaging toggle to ON.
  3. In the Terms of Service page, accept the terms.




Obtaining API Key :


  1. In the main Google APIs Console page, select API Access. You will see a screen that resembles the following:


  1. Click Create new Server key. Either a server key or a browser key should work. The advantage to using a server key is that it allows you to whitelist IP addresses.


  1. Click Create:



  1. Take note of the API key value (YourKeyWillBeShownHere).


You can get Sender ID from Google Developer Console -> Services and APIs Linked Sender’s ID  of your application.


Writing Android Application :




  1. Make the following changes in the application's Android manifest :
    • The com.google.android.c2dm.permission.RECEIVE permission so the Android application can register and receive messages.
    • The android.permission.INTERNET permission so the Android application can send the registration ID to the 3rd party server.
    • The android.permission.GET_ACCOUNTS permission as GCM requires a Google account (necessary only if if the device is running a version lower than Android 4.0.4)
    • The android.permission.WAKE_LOCK permission so the application can keep the processor from sleeping when a message is received. Optional—use only if the app wants to keep the device from sleeping.
    • An applicationPackage + ".permission.C2D_MESSAGE permission to prevent other Android applications from registering and receiving the Android application's messages. The permission name must exactly match this pattern—otherwise the Android application will not receive the messages.
    • A receiver for com.google.android.c2dm.intent.RECEIVE, with the category set as applicationPackage. The receiver should require the com.google.android.c2dm.SEND permission, so that only the GCM Framework can send a message to it. Note that the receiving of messages is implemented as an intent.
    • An intent service to handle the intents received by the broadcast receiver. Optional.
    • If the GCM feature is critical to the Android application's function, be sure to set android:minSdkVersion="8" in the manifest. This ensures that the Android application cannot be installed in an environment in which it could not run properly.


  1. Register for GCM :
    • An Android application running on a mobile device registers to receive messages by calling the GoogleCloudMessaging method register(senderID...). This method registers the application for GCM and returns the registration ID. This streamlined approach replaces the previous GCM registration process.


  1. Write your application :
    • Write the Client Side Code :
      1. Develop an Intent Service, this is a service that will handle all aspects of communication with GCM. Just extend GCMBaseIntentService Here is how Intent Service should look like:
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.android.gcm.GCMBaseIntentService;
public class GCMIntentService extends GCMBaseIntentService {
public GCMIntentService() {
   super(SENDER_ID);


   }
   @Override
   protected void onError(Context arg0, String arg1) {
       Log.e("Registration", "Got an error!");
       Log.e("Registration", arg0.toString() + arg1.toString());
   }
   @Override
   protected void onMessage(Context arg0, Intent arg1) {
       Log.i("Registration", "Got a message!");
       Log.i("Registration", arg0.toString() + " " + arg1.toString());
       // Note: this is where you would handle the message and do something in your app.   
   }
   @Override
   protected void onRegistered(Context arg0, String regId) {
       Log.i("Registration", "Just registered!");
       Log.i("Registration Id - ", regId.toString());  
       // This is where you need to call your server to record the device token and registration id.
//You can locally store dive Id in preference for future access.
   }
   @Override
   protected void onUnregistered(Context arg0, String regId) {
Log.i("Registration", "Device  not registered!");


   }
}


      1. In you Main Activity onCreate operation, check whether device is registered. If not registered, call register method.


private void RegisterWithGCM()
{       
   GCMRegistrar.checkDevice(this);
   GCMRegistrar.checkManifest(this);
   final String regId = GCMRegistrar.getRegistrationId(this);
   if (regId.equals("")) {
     GCMRegistrar.register(this, SENDER_ID); // Note: get the sender id from configuration.
   } else {
        
     Log.v("Registration", "Already registered, regId: " + regId);
   }
}