Find file History

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

This guide builds on top of the GCM sample Quickstart app. If you already have an existing application, then you can reference the Quickstart app as a guide to setting the GCM client code.

To add the backend to your existing Android app from the GCM backend template, open Android Studio 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 the project which contains your Android app. The client module will be set up to call your newly generated backend. The module name which you've entered above (marked with red 1) will be used in your Android Studio project. The 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. 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.

Navigate to http://localhost:8080. 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

To test the application, you need a Google Cloud Messaging API key. Follow the instructions to create a google-services.json configuration file and 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 copy the generated API key into appengine-web.xml file, replacing

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

with

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

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.

Set up your Google Cloud Messaging Client. Follow the guide to obtain a registration token, register the user's device with your new backend, and set up the listener services to show push notifications from the GCM backend.

To send your newly obtained GCM registration token to the server, use the following code snippet which you should invoke from the RegistrationIntentService you created when setting up the client:

    private void sendRegistrationToServer(String token) throws IOException {
        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);
                    }
                });
        Registration regService = builder.build();
        regService.register(token).execute();
    }

2.3. Testing device registration in an emulator

If you have added a RegistrationIntentService invocation to one of your Android app activities (as demonstrated in the Quickstart app), and set up the google-services.json configuration file containing your Google Developers Console project number, you are ready to test the device registration with your backend locally.

First, 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

Next, 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.

You should see the following in your GCM Quickstart app:

Emulator successfully registered with "GcmEndpoints" backend

2.3.1. Testing device registration on a physical device

Testing on a physical device with a local development server requires minor changes to your configuration.

  1. You must make your development server accessible to the network by setting it to listen to external connections. You can do this by editing the build.gradle for the backend project and setting the httpAddress.

    appengine {
      ....
      httpAddress = "0.0.0.0"
      ....
    }
  2. You must also change the endpoint root url to point to your computer's ip address when creating the endpoint .

    Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(),
            new AndroidJsonFactory(), null)
            .setRootUrl("http://<my-computer-address>:8080/_ah/api/")
            ....

2.4. Showing push notifications from GCM backend

You should now be set up to receive push notifications coming from the generated backend. To test this out, ensure your GCM backend is running locally as described in section 1.1, enter a test message, and send:

Send message from GCM backend

You should see a notification arrive in your device emulator:

Receive notification in device emulator

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 the RegistrationIntentService class explained in section 2 above. In particular, replace the lines

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);
            }
        });

with these 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!