How to Add Google Cloud Messaging to your App

Google Cloud Messaging (GCM) is straightforward to add to an application. We put these simple instructions together to help customers get started quickly. You might also want to have a look at Google’s Getting Started with GCM page.

Create a Google API Project

To create a Google API project:

  1. Open the Google APIs Console page
  2. If you haven’t created an API project yet, the page that loads will prompt you to do so:

    If you already have existing projects, the first page you see will be the Dashboard page. From there you can create a new project by opening the project drop-down menu (upper left corner) and choosing Other projects > Create.
  3. Click Create project. Your browser URL will change to something like:
    https://code.google.com/apis/console/#project:4815162342
  4. 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 the GCM Service

To enable the 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.

Credit to: http://developer.android.com/google/gcm/gs.html#client for this section of the instructions.

Add Dependencies

GCM has a dependency on the Google Play Services. In addition there is an optional Google Cloud Messaging for Android library that makes integrating GCM much easier. To add the dependencies:

  1. Start the Android SDK Manager, expand the extras node, check Google Play services and Google Cloud Messaging for Android Library, and click Install packages…
  2. Accept the licenses and click Install.
  3. Right-click on the libs folder of your project and click Import… Expand the General node, select File System and click Next >.
  4. The Google Play service library is installed in the extras folder of the Android SDK. The path relative to the SDK is extras/google/google_play_services/libprojects/google-place-services_lib/libs. Fill the path into the From directory, choose google-play-services.jar and click Finish
  5. Right-click on the libs folder of your project and click Import… Expand the General node, select File System and click Next >.
  6. The Google Cloud Messaing for Android Library is also installed in the extras forlder of the Android SDK. The path relative to the SDK is extras/google/gcm/gcm-client/dist. Fill the path into the From directory, choose gcm.jar and click Finish

Edit your App’s Manifest

You need to make several changes to AndroidManifest.xml for your application to use GCM:

  1. The com.google.android.c2dm.permission.RECEIVE permission so the Android application can register and receive messages.
  2. The android.permission.INTERNET permission so the Android application can send the registration ID to the 3rd party server.
  3. 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)
  4. 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.
  5. 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.
  6. 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.

Here are excerpts from a manifest that supports GCM:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pushspring.sample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />

    <!-- GCM requires a Google account. -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.GET_TASKS" />

    <!-- Creates a custom permission so only this app can receive its messages. -->
    <permission
        android:name="com.pushspring.sample.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.pushspring.sample.permission.C2D_MESSAGE" />

    <!-- This app has permission to register and receive data message. -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <!-- Network State Permissions to detect Internet status -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <!-- Permission to vibrate -->
    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.pushspring.sample.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name="com.google.android.gcm.GCMBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>

                <!-- Receives the actual messages. -->
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <!-- Receives the registration id. -->
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <category android:name="com.pushspring.sample" />
            </intent-filter>
        </receiver>

        <service android:name="com.pushspring.sample.GCMIntentService" />
    </application>

</manifest>

Add a GCMIntentService

You need to add a GCMIntentService to your application. This service receives notification of you application successfully registering, unregistering and receiving messages from GCM. The GCM library provides a base class to derive from so your GCMIntentService can be simple. Here is an example of a GCMIntentService from the PushSpring sample app:

package com.pushspring.sample;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.pushspring.sdk.PushSpring;
import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService {
    public GCMIntentService() {
        super(YOUR_SENDERID);
    }


    @Override
    protected void onError(Context context, String errorMessage) {
        Log.d(getClass().getSimpleName(), "onError: " + errorMessage);
    }

    @Override
    protected void onMessage(Context context, Intent message) {
        Bundle extras=message.getExtras();
         for (String key : extras.keySet()) {
              Log.d(getClass().getSimpleName(),
                    String.format("onMessage: %s=%s", key,
                                  extras.getString(key)));
         }
     }

    @Override
    protected void onRegistered(Context context, String registrationId) {
        Log.d(getClass().getSimpleName(), "onRegistered: " + registrationId);
    }

    @Override
    protected void onUnregistered(Context context, String registrationId) {
        // TODO Auto-generated method stub
        Log.d(getClass().getSimpleName(), "onUnregistered: " + registrationId);
    }
}

Replace YOUR_SENDERID with your SenderId. You will need to add code in the onRegistered override to send the registrationId to your server. You will also need to add code to the onMessage override to display any messages received from GCM. The PushSpring SDK takes care of this for you and provides functions to call in the SDK from each of these overrides.

Register with GCM

Upon starting up your application must register with GCM. In your applications main activity’s onCreate you need to call the GCMRegistrar to register your SenderId with GCM. Here is an example of the registration code:

final String registrationId = GCMRegistrar.getRegistrationId(this);
if(registrationId.length()==0)
{
    // If we failed to get it assume we need to register separately
    GCMRegistrar.register(this, SENDERID);
}

You are done! Time to add PushSpring to leverage GCM!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s