Google Cloud Platform

How to build a mobile app with an App Engine backend

This tutorial describes how to develop a mobile application with backend services hosted on Google App Engine and accessed through Google Cloud Endpoints. It includes sample code for the backend service as well as iOS and Android mobile apps.


The example app used in this tutorial is the Mobile Shopping Assistant. The app lets users get information on products at the store they are in, as well as find nearby stores.

The app includes custom code to wire the basic app client to the App Engine cloud backend, using Google Cloud Endpoints. The app can then determine user location, locate nearby stores, and allow the user to obtain relevant offers and recommendations.

The following figure shows the main components of the sample app.

Mobile clients
    connected to App Engine through Cloud Endpoints

Target Audience

This tutorial is directed to any developer interested in learning how to build services in the cloud and use them from mobile applications which give to the customers a more engaging environment and better experience.

You need to know how to program in Java. Also, you should be familiar with building mobile apps (Android or iOS, depending on your target platform). A basic knowledge of App Engine technology is not required but is a plus.


Make sure you have installed the following tools and packages for the tutorial:

  • Android Studio version 1.0 or higher.
  • Checkstyle IDEA (optional), which provides both real-time and on-demand scanning of Java files with CheckStyle 6.5. Or, Stock Android Studio, with checkstyle-idea plugin and Android SDK 21 installed.

Download Sample Code

To follow along with the tutorial, download the code from Mobile Shopping Assistant.

App Engine Backend

This section describes how to set up the mobile backend app which runs on Google Cloud Platform (App Engine). The application contains the data repository and the business logic to support the mobile client requests. In this tutorial you use Android Studio to set up and deploy the backend that will be used by both the Android and the iOS clients.

Using Android Studio to set up the backend (for both clients) has the following advantages:

  • Android Studio gives you direct integration with App Engine.
  • Through Android Studio, you can auto-generate the Cloud Endpoints client libraries needed to access the backend.

Create the backend project

To create the backend project in Android Studio, follow the instructions in Add a Cloud Messaging Module. The package name can be something like

Write the backend

Now you're ready to start building the application by creating the entity classes that represent the app's backend data. An entity class provides an “object-relational interface” between your application and the backend data repository.

The backend module in the Mobile Shopping Assistant sample app includes the following packages with the following contents:

  • —This package includes the entity files that map to persistent data objects:
    • CheckIn
    • Offer
    • Place
    • PlaceInfo
    • Recommendation
    • Registration
    • UserAccount
  • —Contains Endpoint files that expose REST APIs for particular resources, such as CheckIn, Place, Offer, Recommendation, and Messaging (for Google Cloud Messaging messages between the app and a registered device).
  • — CheckInUtil, EndpointUtil, PlacesHelper.
  • Constants—Stores all API keys and IDs
  • EndpointUtil—checks authentication of a user.
  • OfyServiceObjectify service wrapper that makes it possible to statically register persistence classes.

You create an entity class as desribed in the following section. You repeat the process for each of the entities.

Create an entity class

The examples in this section are based on the Checkin entity. You need to create an entity class for each of the entities in your app. To create an entity class:

  1. In the Package Explorer, navigate to the models folder under your backend project, and select File > New > Java Class. The New Java Class wizard is displayed.
  2. In the Name: box enter the name of the class that will represent the entity, for example, CheckIn.
  3. Click Okay.
  4. In the editor, replace the boiler plate code with the code for the class that you can obtain from the downloaded sample. Notice that the code shown provides a “ready to run” class. The most important things you must pay attention to are the properties and the annotations.
  5. Save the class.

Generate a Cloud Endpoints Class

For each entity class, you need to generate a Cloud Endpoints class to give your client app access to backend data. To generate a Cloud Endpoints class:

  1. Create a class CheckInEndpoint in the backend/apis package.
  2. Open src/main/webapp/WEB-INF/web.xml and add the new class full path in the <param-value> section, as follows:
  3. <servlet>
  4. Open the Objectify service class In the static bit, add the line ObjectifyService.register(CheckIn.class) to register the CheckIn class as persistent:
    public final class OfyService {
         * Default constructor, never called.
        private OfyService() {
        static {
         * Returns the Objectify factory service.
         * @return The factory service.
        public static ObjectifyFactory factory() {
            return ObjectifyService.factory();

Android Client

This section gives an overview of creating an Android client app that can communicate with your App Engine backend.

Create Android client project

The mobile client application provides the interface that allows the customer to interact with the backend, for example to obtain sales information.

To create a mobile client app project:

  1. In Android Studio, select File > New Project.
  2. The New Project wizard window is displayed.
  3. In the Application Name box, enter the name of your application, for example MobileAssistant.
  4. In the Package Name box, enter the name of your application’s package, for example
  5. In the Target Android Devices dialog, accept the default values for form factor and minimum SDK, and click Next.
  6. In the Add an activity to Mobile dialog, accept the "blank activity" default selection, and click Next.
  7. In the Customize the activity dialog, make any desired edits to your activity, and click Finish.

Display Places data

In Android Studio, navigate to the android project and open It includes an AsyncTask called ListOfPlacesAsyncRetriever that retrieves the list of nearby places (e.g., stores) from the and updates the corresponding ListView (client app UI) and label. ListOfPlacesAsyncRetriever is called from MainActivity's onCreate() method.

The variable placesList contains the information obtained from the backend.

The client application instantiates the ListOfPlacesAsyncRetriever class at the creation time and calls its execute method (in the onCreate() method).

The client app makes asynchronous API calls when a customer checks into a place. In the example code, it retrieves places information from the backend.

Modify activity_main.xml

The backend results that are retrieved in MainActivity are mapped to the app UI via the app's XML resource files:

  1. In the sample app in Android Studio, expand the res folder and then the layout folder.
  2. Open the activity_main.xml file. This excerpt maps the backend places data retrieved in onCreate to the client app's UI:

This defines a ListView UI element that displays the list of stores.

The final step is to wire the placesList variable in OnCreate to the ListView in activity_main.xml:

placesList = (ListView) findViewById(;

This allows access to the widget so you can set new content (the list of stores). Notice, you can open the activity_main.xml file using the Android XML (visual) editor and you can assign the value @+id/PlacesList to the Id property.

Here are the XML resource files that define the UI for the app:

  • activity_main.xml. This file is in the res/layout folder and defines the UI layout for buttons, and places list.
  • place_item.xml. This file is in the res/layout folder and contains information about display format and position for the places.
  • strings.xml. This file is in the res/values folder and contains predefined strings to display on various occasions.

To learn more creating a UI in an Android app, see the Android user interface developer guide.

Display places detail view

The placesListClickListener event handler is invoked when the customer clicks on an item in the list of nearby places. The handler asynchronously checks the customer into the selected place and navigates to the activity that will present details about this place:

import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
     * Event handler invoked when user clicks on an item in the list of nearby
     * places. It asynchronously checks the user into the selected place and
     * navigates to the activity that will present details about this place.
    private OnItemClickListener placesListClickListener
            = new OnItemClickListener() {
        public void onItemClick(final AdapterView<?> arg0, final View arg1,
                final int arg2, final long arg3) {
            PlaceInfo selectedPlace = places.get((int) arg3);

            new CheckInTask().execute(selectedPlace);

            Intent i = new Intent(MainActivity.this,

In the onCreate() method, the handler is set as follows:

placesList = (ListView) findViewById(;

Note that the placesListClickListener event handler starts a new Activity to display the Places UI. All activities must be defined in AndroidManifest.xml:

<activity android:name=
"" >

The class performs tasks such as retrieving offers and recommendations asynchronously. The class asynchronously retrieves the list of offers and recommendations through the appropriate endpoints and update the corresponding ListView and label for each:

import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.TextView;

  * The class automatically generated by the Google App Engine backend
  * project, used to access the API easily from the Android application.
  private ShoppingAssistant shoppingAssistantAPI;

private static PlaceInfo currentPlace;
private ListView offersList;
private ListView recommendationsList;
private TextView placesNameLabel;
private TextView offersListLabel;
private TextView recommendationsListLabel;

  * Initializes the activity content, binds relevant widgets and starts
  * asynchronously retrieving offers and recommendations.
protected final void onCreate(final Bundle savedInstanceState) {

    shoppingAssistantAPI = CloudEndpointBuilderHelper.getEndpoints();

    offersList = (ListView) findViewById(;
    recommendationsList = (ListView) findViewById(;

    placesNameLabel = (TextView) findViewById(;
    offersListLabel = (TextView) findViewById(;
    recommendationsListLabel = (TextView) findViewById(



  * Retrieves the list of offers through appropriate CloudEndpoint.
  * @param params the place for which to retrieve offers.
  * @return collection of retrieved offers.
    protected OfferCollection doInBackground(final PlaceInfo... params) {
        PlaceInfo place = params[0];

        if (place == null) {
            return null;

        OfferCollection result;

        try {
            result = shoppingAssistantAPI.offers().listOffers().execute();
        } catch (IOException e) {
            return result;

Similar code applies to the recommendations collection.

Deploy the Sample App

This section describes how to deploy and run the sample app. Here is an overview of the steps:

  1. Download the sample app, and add the necessary values and credentials.
  2. Build and deploy the backend.
  3. Populate the datastore with data.
  4. Rebuild the datastore index. Look in Datastore Entities in the Google Cloud Platform Console to ensure that the datastore contains the expected data.
  5. Run the app on a connected device or in the emulator.

These steps are described in more detail in the following sections.

Download and set up sample app

Download the code from the MobileAssistantAndroidAppEngine folder in Mobile Shopping Assistant.

Before you can run the sample app, you need to add the necessary IDs and credentials to your version of the app:

  1. Create the new project.
  2. Obtain a GCM_API_KEY as described in the table below, and follow the Cloud Endpoints documentation to obtain the Client IDs ANDROID_CLIENT_ID, IOS_CLIENT_ID, and WEB_CLIENT_ID. For the Android Client ID the package name is, and for the iOS Client ID the bundle is
  3. Open MobileAssistantAndroidAppEngine/backend/src/main/webapp/WEB-INF/appengine-web.xml and enter your APPLICATION_ID within the application XML element and the GCM_API_KEY within the gcm.api.key XML element.
  4. Open MobileAssistantAndroidAppEngine/backend/src/main/java/com/google/sample/mobileassistantbackend/ and insert the API keys and IDs required.
  5. Open MobileAssistantAndroidAppEngine/android/config.gradle and insert SENDER_ID, WEB_CLIENT_ID, and the URL to your deployed application, which is, and set SIGN_IN_REQUIRED to "true".

The following table summarizes the edits you need to make to the files in the sample app.

Constant Credential Details
Google Cloud Messaging

To obtain a Google Cloud Messaging API key:

  1. In the Credentials page in the Cloud Platform Console, click Add credentials and select API key.
  2. Click Server key.
  3. Supply your server's IP address or range of allowed IPs in the Accept requests from these server IP addresses field or leave blank for testing from any IP address
  4. Click Create.
  5. Copy the key.

Add the API key to your config file:


SENDER_ID Sender ID (project number)

This is the project number associated with your project ID in the Cloud Platform Console.

Add to:

APPLICATION_ID The project ID for the project you created in the Cloud Platform Console.

Add to:

Web Client


Add to:
config.gradle and

AUDIENCE_ID Web client ID Instructions
Android Client


Add to:

Build and deploy the backend

In Android Studio select Build > Deploy module to App Engine and follow the instructions. For details, see Running, Testing, and Deploying the Backend.

Populate the datastore with data

The sample app includes CSV files that you use to populate the data store with stores, offers, and recommendations.

To insert data into the backend:

  1. Locate the CSV files in your downloaded sample app. They are under ~/MobileShoppingAsst-app/MobileShoppingAssistant-sample-master/MobileAssistantAndroidAppEngine/backend/MobileAssistant-Data.
  2. Edit the files if you want to add your own sample data to them.
  3. Open a terminal and type gcloud auth login to authenticate using the account you've designated as the app's admin account.
  4. cd to the directory containing the CSV files, and run the following commands to upload the CSV data to the backend: upload_data --config_file bulkloader.yaml --url=http://<sample_url>/remote_api --filename places.csv --kind=Place -e <admin_email_address> upload_data --config_file bulkloader.yaml --url=http://<sample_url>/remote_api --filename recommendations.csv --kind=Recommendation -e <admin_email_address> upload_data --config_file bulkloader.yaml --url=http://<sample_url>/remote_api --filename offers.csv --kind=Offer -e <admin_email_address

Note the following:

  • It will prompt you to log in. Don't skip this step.
  • The sample URL is based on your project. For example:
  • Note that each command applies to a different kind of data. Be sure to specify the correct kind; this information is used by the database.

Rebuild the index

To make your freshly updated data available to the app:

  1. Make sure you are signed in using your app admin account.
  2. Go to https://<sample_url>/admin/buildsearchindex. For example,

Check the data store in the Cloud Platform Console

To make sure that the data uploaded correctly:

  1. Open Datastore Entities in the Cloud Platform Console.
  2. From the Kind drop down menu, check Place, Recommendation, and Offer to make sure that your data uploaded successfully.

Test locally

If desired, you can test your backend setup locally, as follows:

  1. In the config.gradle file in Android Studio, set the following values:
    buildConfigField "String", "ROOT_URL",
    buildConfigField "boolean", "SIGN_IN_REQUIRED", "false"

    Note: Don't forget to change these values back before deploying the app.

  2. Follow the steps in Populate the datastore with data, but instead of specifying a URL based on your project ID, use your localhost URL. For example, this command adds data for Place: upload_data --config_file bulkloader.yaml --url=http://localhost:8080/remote_api --filename places.csv --kind=Place -e <admin_email_address>
  3. Rebuild your datastore index, as described in Rebuild the index, but use your localhost URL:
  4. Start the backend.
  5. Run your app using the emulator (a connected device won't work for testing locally).
  6. Go to http://localhost:8080/_ah/admin and navigate to Datastore Viewer to verify that your local datastore contains the expected data. You must be signed in with your admin password.

Run the app

To run the sample app with the backend deployed in the cloud:

  1. Build the backend, then select Build > Deploy module to App Engine and follow the instructions. You will need to login from Android Studio into your admin account.
  2. Run the application.

iOS Client

The Mobile Shopping Assistant iOS Client demonstrates how to build an iOS client that mirrors the functionality of the Android client by leveraging the same Google App Engine backend with the help of Google APIs Client Library for Objective-C.

Project setup, installation, and configuration

This sample source code and project is designed to work with Xcode 6.2. The application was tested on iOS 8.2.


Follow the instructions in Deploy the Sample App and deploy the backend to Google App Engine. Note that the Bundle ID for this iOS client is

Make sure you have correctly imported sample data to the deployed backend following MobileAssistantAndroidAppEngine/backend/MobileAssistant-Data/

Set up Mobile Assistant iOS Client Xcode project

Open MobileAssistantIOS project in Xcode

Open a new Finder window and navigate to the directory you have extracted the Mobile Assistant iOS Client. Double click on the MobileAssistantIOS.xcodeproj file. It will open the project in Xcode automatically.

Configure Mobile Assistant Backend to recognize the iOS client app

  1. The Mobile Assistant Backend was configured to use a particular IOS_CLIENT_ID in step 2 of the Prerequisites.
  2. Look up the client secret, that corresponds to the IOS_CLIENT_ID in the backend, from Cloud Platform Console, update the following constants in the ShopsTableViewController.m file in the MobileAssistantIOS project:
    • kKeyClientID (in line 35)
    • kKeyClientSecret (in line 36)
  3. In the MobileAssistantIOS/API/GTLServiceShoppingAssistant.m file, replace the string "{{{YOUR APP ID}}}" with the Application ID of where the Mobile Assistant Backend was deployed.
  4. Follow the steps at Using Endpoints in an iOS Client. See step 1, If you are not using the Google+ iOS SDK.

Build and execute the MobileAssistantIOS project

  1. Follow the steps to set the simulator location to San Francisco, CA.
  2. On the top left corner of the toolbar in Xcode, select MobileAssistantIos.

    iPhone 8.2 Simulator. Click the Run button to execute the app.

  3. Switch to the iOS Simulator application from Xcode. You can now interact with the MobileAssistantIOS Client App.
  • Since this application is location-sensitive, to work with existing data in the Mobile Assistant Backend, set the location to {Latitude: 37.2222, Longtitude: -122.1111} via the menu Debug > Location > Custom Location…
  • If prompted, click "OK" to allow MobileAssitantIOS app to access your current location.
  • The application may ask for your Google Account information. Sign in and consent to allow the application to view your email address and know who you are on Google.
  • On the first screen, click any store location. On the next screen, the application will display different recommendations and offers based on different store location.

Take a closer look at MobileAssistantIOS client app

In ShopsTableViewController.m file, set breakpoints to the following methods:

  • fetchAllShops
  • fetchOffersForPlaceID
  • fetchRecommendationsForPlaceID

These methods are responsible for making the requests to the Mobile Assistant Backend via the Google APIs Client Library for Objective-C.

Optional reference

Click here to learn more about generating iOS client library for Google Cloud Endpoint.

Additional Resources

For more information about the technology behind the tutorial, check out these resources:

Cloud Tools for Android Studio

The Cloud Tools for Android Studio documentation describes how to create and deploy cloud-connected Android apps using Android Studio.

App Engine

  • Google Cloud Endpoints allow you to define business logic on App Engine and access it via RESTful or RPC APIs on multiple platforms including Android, IOS and JavaScript. For more information, see Overview of Google Cloud Endpoints.
  • Getting started. Google App Engine lets you run web applications on Google's infrastructure. For beginner’s information, see What is Google App Engine?


For introductory information on writing Android apps, see Getting Started. You'll find instructions that describe how to accomplish a specific task with code samples you can reuse in your application.