Tuesday, 16 December 2014

HB Blog 43: Google Cloud Messaging (GCM) Client Integration For Android Devices.

Google Cloud Messaging (GCM) for Android 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.A Google Cloud Messaging (GCM) client is a GCM-enabled app that runs on an Android device. A full GCM implementation requires both a client implementation and a server implementation.

In this blog post, I would talk about a Google Cloud Messaging (GCM) client implementation specifically.

A GCM implementation includes a Google-provided connection server, a 3rd-party app server that interacts with the connection server, and a GCM-enabled client app running on an Android device.

The steps involved in writing a GCM client-side application are as follows:
1)Set up Google Play Services using its SDK.
2)Add the following to your application's manifest:
   a)Android permissions related to Internet, register and receive messages, Google account, wake lock, GCM Framework, etc. 
   b)A receiver for com.google.android.c2dm.intent.RECEIVE.
   c)A Service (typically an IntentService) to which the WakefulBroadcastReceiver passes off the work of handling the GCM message.
3)Finally, write your application code for checking Google Play Services APK, register for GCM, send a message, receive a message, etc.

I have added a sample example in this post that implements GCM client services by sending device information as well as gcm notification id to the server and in return server will send message which will be displayed in form of notification on client device.

Have a look on few code snippets,
GCMIntentService.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
public class GCMIntentService extends GCMBaseIntentService {
    String TAG="GCM";
    @Override
    protected void onError(Context arg0, String arg1) {
 try {
     Log.v(TAG, "onError() "+arg1);
 } catch (Exception e) {
     e.printStackTrace();
 }
    }

    @Override
    protected void onMessage(Context context, Intent intent) {
 try {
     String action = intent.getAction();
     Log.v(TAG, "onMessage() "+action);
     if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
  Log.v(TAG,"Handle Registration");
     } else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
  Log.v(TAG,"intent.getExtras() "+intent.getExtras());

  /**Show notification.*/
  String messageText= intent.getStringExtra("message")+"";
  NotificationManagerGCM notificationManagerGCM=new NotificationManagerGCM();
  if(messageText!=null && !messageText.equalsIgnoreCase("") && !messageText.equalsIgnoreCase("null"))
  {
      notificationManagerGCM.showNotificationRemoveableGCM(context,messageText);
  }
  else
  {
      notificationManagerGCM.showNotificationRemoveableGCM(context,"Notification Message GCM Demo");
  }
     }
 } 
 catch (Exception e) {
     e.printStackTrace();
 }
    }

    @Override
    protected void onRegistered(Context arg0, String arg1) {
 try {
     Log.v(TAG, "onRegistered() "+arg1);
 } catch (Exception e) {
     e.printStackTrace();
 }

    }

    @Override
    protected void onUnregistered(Context arg0, String arg1) {
 try {
     Log.v(TAG, "onUnregistered() "+arg1);
 } catch (Exception e) {
     e.printStackTrace();
 }

    }

    @Override
    protected String[] getSenderIds(Context context) {
 String[] ids = new String[1];
 NotificationManagerGCM managerTXTShield=new NotificationManagerGCM();
 ids[0] = managerTXTShield.getGCMSenderID(context);
 return ids;
    }

}

AccountManager.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
public class AccountManager
{
    Context mContext;
    Resources mResources;
    String url,apiKey;

    public AccountManager(Context mContext){
 this.mContext = mContext;
 mResources = mContext.getResources();
 url = mContext.getResources().getString(R.string.url);
 apiKey = mContext.getResources().getString(R.string.api_key);

    }

    /**
     * This method is used to send device information for gcm notification.
     * 
     * @param context
     * @param user_id
     * @return
     */
    public String requestDeviceRegistration(Context context)
    {
 String responseStr = "";
 try{
     // Create a new HttpClient and Post Header
     HttpClient httpclient = new DefaultHttpClient();
     HttpPost httppost = new HttpPost(url);
     try{
  Utility utility = new Utility();
  String unique_device_id = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
  if(unique_device_id == null || unique_device_id.equalsIgnoreCase("null") || unique_device_id.equalsIgnoreCase("")){
      unique_device_id = utility.getDeviceSerialNumber();
  }
  String device_name = utility.getDeviceName();
  String model_no = utility.getDeviceModelName();
  String device_os_version = utility.getDeviceSDKVersion();
  String notification_id = utility.getNotificationID(context);    
  PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
  String app_version = pInfo.versionName;

  System.out.println("apiKey: "+apiKey);
  System.out.println("unique_device_id: "+unique_device_id);
  System.out.println("notification_id: " + notification_id);
  System.out.println("device_name: "+device_name);
  System.out.println("model_no: "+model_no);
  System.out.println("device_os_version: "+device_os_version);
  System.out.println("app_version: "+app_version);


  // Add your data
  List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
  nameValuePairs.add(new BasicNameValuePair("unique_device_id", unique_device_id));
  nameValuePairs.add(new BasicNameValuePair("notification_id", notification_id));
  nameValuePairs.add(new BasicNameValuePair("device_name", device_name));
  nameValuePairs.add(new BasicNameValuePair("model_no", model_no));
  nameValuePairs.add(new BasicNameValuePair("device_os_version", device_os_version));
  nameValuePairs.add(new BasicNameValuePair("app_version", app_version));

  httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

  // Execute HTTP Post Request
  HttpResponse httpResponse = httpclient.execute(httppost);

  HttpEntity responseEntity = httpResponse.getEntity();
  if(responseEntity != null){
      responseStr = EntityUtils.toString(responseEntity);
  }
     }
     catch(Exception e){
  e.printStackTrace();
     }
 }
 catch(Exception e){
     e.printStackTrace();
 }
 return responseStr;
    }
}

Refer the below link for complete sample code:-
Download Sample Code
Download Apk File

No comments:

Post a Comment