Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master

Fix issue 44

Added instructions to swap the placeholder application ID in
appengine-web.xml with the user's project ID.
latest commit 8002ae7ee5
@patflynn patflynn authored

README.md

"App Engine Backend with Google Cloud Messaging" Template

Google Cloud Messaging (GCM) is a service that allows you to send push notifications from your server to your users' Android devices, 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.

This backend template employs Google Cloud Endpoints to define a RESTful API which registers Android devices with your GCM server and allows you to send string messages to registered devices. After defining this API, strongly-typed client libraries are generated automatically and can be called from your Android app, as described below.

1. Adding a backend in Android Studio

To add the backend to your existing Android app from this backend template, open Android Studio (installation instructions) and navigate to "File → New Module..." or right-click on your project and choose "New → Module".

New → Module

In the "New Module" wizard that appears, choose "Google Cloud Module":

Add App Engine Backend Choose Module

Then choose "App Engine Backend with Google Cloud Messaging".

App Engine GCM Module

Enter the module/package names for your new backend, and choose the "client" module in your project which contains your Android app. The client module will be set up to call your newly generated backend. Module name which you've entered above (marked with red 1) will be used in your Android Studio project. Package name (marked with red 2) will be used for all classes imported from this template and (reversed) for Endpoints API namespaces. In turn, Endpoints API namespaces will be used to derive the name of the autogenerated Android client libraries, hence this ensures that the names of generated client libraries will match your package name.

Added "GcmEndpoints" backend. Red numbers 1 and 2 indicate that the module name and the package names came from "New App Engine Module" dialog

1.1. Debugging the backend locally

As soon as the backend module is added to your project and Gradle sync finishes, a new run configuration with your backend's module name should be created:

Created run configuration

Rebuild your project (via "Build → Rebuild Project") and launch this run configuration. It will invoke appengineRun task in Gradle plug-in for App Engine, which in turn will start the local App Engine Java development server.

To ensure that your backend started successfully, navigate to http://localhost:8080. If everything went well, you should see the following page:

"HelloWorld" backend running in local Java development server

2. Connecting your Android app to the backend

2.1. Obtaining Google Cloud Messaging API key

Before testing the application, you will need to obtain a Google Cloud Messaging API key. Open the <backend>/src/main/webapp/WEB-INF/appengine-web.xml file (it should have been opened by default when you generated the backend), and navigate to this link: https://console.developers.google.com/flows/enableapi?apiid=googlecloudmessaging&keyType=SERVER_SIDE&r=0.0.0.0/0.

Project creation in Google Developers Console

Choose a "Create a new project" option to create a new Google Developers Console project (or choose an existing project, if you have one already), and click "Continue".

Read the Terms of Service and assuming that you agree, check the checkbox to indicate that you have read them and click "Accept".

Once you select or create a project, it will have "Google Cloud Messaging for Android" API enabled automatically. In the following configuration dialog, you can use the supplied "0.0.0.0/0" IP address for testing purposes.

Creating a new server key in Google Developers Console

Click "Create" to get the API key for server applications generated for you.

Server applications API key in Google Developers Console

Copy the generated API key (in a red rectangle, starts with AIza...) back into appengine-web.xml file, replacing

<property name="gcm.api.key" value="YOUR_KEY_HERE"/>

with

<property name="gcm.api.key" value="AIza..."/>

Finally, go back to your project's overview in Google Developers Console and note down the project number (in red rectangle below): this will be your Google Cloud Messaging sender ID in the next step.

Project number in Google Developers Console

2.2. Registering devices with Google Cloud Messaging backend

Before any messages can be sent from a Google Cloud Messaging backend to the devices, these devices need to be registered with a GCM backend.

When you added this backend module to your project, the required permissions, needed by Google Cloud Messaging have been added into the Android manifest of your app, and the required build dependencies have been added to your app's build.gradle file.

Furthermore, a RegistrationEndpoint Cloud Endpoints API has been automatically generated for you, so that you could start calling this endpoint from your Android app to register devices with your new Google Cloud Messaging backend.

Here is an example code snippet which illustrates how to create an AsyncTask to register the user's device with your new backend:

class GcmRegistrationAsyncTask extends AsyncTask<Void, Void, String> {
    private static Registration regService = null;
    private GoogleCloudMessaging gcm;
    private Context context;

    // TODO: change to your own sender ID to Google Developers Console project number, as per instructions above
    private static final String SENDER_ID = "1234567890123";

    public GcmRegistrationAsyncTask(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(Void... params) {
        if (regService == null) {
            Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(),
                    new AndroidJsonFactory(), null)
                // Need setRootUrl and setGoogleClientRequestInitializer only for local testing,
                // otherwise they can be skipped
                .setRootUrl("http://10.0.2.2:8080/_ah/api/")
                .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
                    @Override
                    public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest)
                            throws IOException {
                        abstractGoogleClientRequest.setDisableGZipContent(true);
                    }
                });
                // end of optional local run code

            regService = builder.build();
        }

        String msg = "";
        try {
            if (gcm == null) {
                gcm = GoogleCloudMessaging.getInstance(context);
            }
            String regId = gcm.register(SENDER_ID);
            msg = "Device registered, registration ID=" + regId;

            // You should send the registration ID to your server over HTTP,
            // so it can use GCM/HTTP or CCS to send messages to your app.
            // The request to your server should be authenticated if your app
            // is using accounts.
            regService.register(regId).execute();

        } catch (IOException ex) {
            ex.printStackTrace();
            msg = "Error: " + ex.getMessage();
        }
        return msg;
    }

    @Override
    protected void onPostExecute(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
        Logger.getLogger("REGISTRATION").log(Level.INFO, msg);
    }
}

Don't forget to replace SENDER_ID in the snippet above with your actual Google Developers Console project number!

To make the actual registration call from your app, invoke this AsyncTask from one of your Android activities. For example, to execute it from MainActivity class, add the following code snippet to MainActivity.onCreate method:

new GcmRegistrationAsyncTask(this).execute();

2.3. Testing device registration in an emulator

If you have added an GcmRegistrationAsyncTask invokation to one of your Android app activities as per steps above (and replaced SENDER_ID with your actual Google Developers Console project number), you should be all set to test the device registration with your backend locally!

To begin with, make sure that your Android Virtual Device is using Google APIs System Image as illustrated in the screenshot below.

Android Virtual Device configuration containing Google APIs System Image Target

Then, launch your backend locally as described in section 1.1. and ensure that you can access it via http://localhost:8080. If you can access the backend locally, change the run configuration back to your Android app and run the Android emulator.

If everything goes well, you should see the following toast in your app:

Emulator successfully registered with "GcmEndpoints" backend

2.4. Showing push notifications from GCM backend

In order to show the push notifications coming from the generated backend, you need to add two more simple classes into your Android client: GcmIntentService and GcmBroadcastReceiver.

Here is the source code for GcmIntentService.java:

public class GcmIntentService extends IntentService {

    public GcmIntentService() {
        super("GcmIntentService");
    }

    @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 (extras != null && !extras.isEmpty()) {  // has effect of unparcelling Bundle
            // Since we're not using two way messaging, this is all we really to check for
            if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                Logger.getLogger("GCM_RECEIVED").log(Level.INFO, extras.toString());

                showToast(extras.getString("message"));
            }
        }
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

    protected void showToast(final String message) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
            }
        });
    }
}

Similarly, here is the source code for GcmBroadcastReceiver.java:

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Explicitly specify that GcmIntentService 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);
    }
}

After adding these classes to your Android application, register them by adding the following snipped into your AndroidManifest.xml file (inside <application> tag).

<receiver
    android:name=".GcmBroadcastReceiver"
    android:permission="com.google.android.c2dm.permission.SEND" >
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <category android:name="MY_PACKAGE" />
    </intent-filter>
</receiver>
<service android:name=".GcmIntentService" />

Do not forget to replace MY_PACKAGE in the snippet above with your package name.

2.5. Deploying the backend live to App Engine

If your backend is working locally, you can deploy it to Google App Engine.

  1. Stop the backend, if it is running locally, by selecting Run > Stop.

  2. Run Build > Deploy Module to App Engine.

Deploy module to App Engine

  1. In the Deploy to App Engine dialog, select your module. From the Deploy To: dropdown list, choose "Click here to create a new Google Developers Console project." This will open Google Developers Console

    • If you are running this task for the first time, you will be prompted to sign-in with your Google Account. Choose an account and sign in.
  2. Create a new project and switch back to the Deploy to App Engine dialog in Android Studio.

  3. This would probably be a good time to update your src/main/webapp/WEB-INF/appengine-web.xml file's <application> property and replace myApplicationId with the ID of the project that you just created. This will be important if you try to deploy from the command line.

  4. Click the Refresh button Deploy module to App Engine in the bottom right corner of the Deploy To: dropdown list and then select the project you just created.

  5. Click Deploy. You can monitor the status of your deployment in the Android Studio console.

2.6. Testing against a deployed backend

Once you have deployed your backend to App Engine, you can connect your Android app to it by modifying GcmRegistrationAsyncTask class defined in section 2 above. In particular, replace the lines

Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
        .setRootUrl("http://10.0.2.2:8080/_ah/api/") // 10.0.2.2 is localhost's IP address in Android emulator
        .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
            @Override
            public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
                abstractGoogleClientRequest.setDisableGZipContent(true);
            }
        });

with these two lines

Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
        .setRootUrl("https://android-app-backend.appspot.com/_ah/api/");

where android-app-backend corresponds to your own Project ID created in section 2.5.

At this point you should be all set to run your Android app in an emulator or on the physical device, and successfully communicate with your new App Engine backend!

Something went wrong with that request. Please try again.