Monday, March 23, 2015

Google Cloud Messaging

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.






Steps to follow to receive GCM notification in Android Client App

1. Write Broadcast Receiver class which extends WakefulBroadcastReceiver and handle the intent action in onReceive method

Please refer below example

Declare the components in AndroidManifest.xml

<!-- GCM Push Notification -->

<!-- Broadcast Receiver to receive the GCM notification from GCM Agent -->
<receiver
 android:name=".notification.GcmPushNotificationReceiver"
 android:permission="com.google.android.c2dm.permission.SEND" >
 <intent-filter>
  <action android:name="com.google.android.c2dm.intent.RECEIVE" />
 </intent-filter>
</receiver>

<!-- Service to handle in intent action -->
<service android:name="notification.GcmIntentService" >
</service>
<!-- GCM Push Notification -->

GcmPushNotificationReceiver.java

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;

public class GcmPushNotificationReceiver extends WakefulBroadcastReceiver {
 
 private static final String TAG = GcmIntentService.class.getSimpleName();

 @Override
 public void onReceive(Context context, Intent intent) {
  if(Debug.DEBUG_LOW) Log.i(TAG, "onReceive action = "+intent.getAction());
     // Explicitly specify that GcmMessageHandler will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(),
          GcmIntentService.class.getName());
        
        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
 }
}

GcmIntentService.java

import com.google.android.gms.gcm.GoogleCloudMessaging;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;


public class GcmIntentService extends IntentService {
 
 private static final String TAG = GcmIntentService.class.getSimpleName();

 public GcmIntentService(String name) {
  super(name);
 }

 @Override
 protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent);
        if(Debug.DEBUG_LOW) Log.i(TAG, "GcmIntentService Received : (" +messageType+")  "+extras.getString("title"));
        
        GcmPushNotificationReceiver.completeWakefulIntent(intent);
 }

}

0 comments:

Post a Comment