HelloEndpoints with Android Studio

We recommend that you use the latest version of this feature, which is renamed to Cloud Endpoints Frameworks for App Engine. This new version supports App Engine standard environment, provides lower latency, and has better integration with App Engine. For more details, see Migrating to 2.0.

This tutorial introduces you to the basics of using Cloud Endpoints. It uses Android Studio and Cloud Tools for Android Studio.

Objectives

In this tutorial you will learn how to:

  1. Build an backend API in Android Studio using Cloud Endpoints.
  2. Connect an Android app to the backend API.
  3. Test and deploy the backend API.

Costs

App Engine has free a level of usage. If your total usage of App Engine is less than the limits specified in the App Engine free quota, there is no charge for doing this tutorial.

Before you begin

  1. Install Android Studio.
  2. Create or select a Cloud Platform project in the Cloud Platform Console and then ensure that project includes an App Engine application:

    Go to App Engine

    The Dashboard opens if an App Engine application already exists in your project. Otherwise, you are prompted to choose the region where you want your App Engine application located.

  3. Note the ID of your Cloud Platform project because you need the ID to deploy your app.

Adding a backend using Android Studio

To add a backend:

  1. Open Android Studio and select File > New > Module.

    Android Studio context menu

  2. In the New Module wizard, choose Google Cloud Module.

    New Module wizard

  3. Configure your module as follows:

    1. From the Module type dropdown menu, choose App Engine Java Endpoints Module.
    2. Enter backend for the Module name.
    3. Enter com.google.sampleapp.backend for the Package name.
    4. From the Client module dropdown menu, choose app.

    New Module wizard

The resulting client module is set up to call your new backend. The module name (marked with a red 1) is used in your Android Studio project. The package name (marked with a red 2) is used for all classes imported from this template and (reversed) for Endpoints API namespace. In turn, Endpoints API namespace is used to derive the name of the autogenerated Android client libraries, which ensures the name matching between the generated client libraries and your package name.

Module wizard output

Debugging the backend locally

Adding the backend module also creates a new run configuration for the backend:

The new run configuration

To debug the backend using the run configuration:

  1. Rebuild your project (via Build > Rebuild Project).
  2. Launch the run configuration for your backend. The launch invokes appengineRun in the Gradle plug-in for App Engine, which starts the local App Engine Java development server.
  3. In your browser, navigate to http://localhost:8080 to see the following:

    Hello Endpoints default page

Connecting your Android app to the backend

When you create a backend module, strongly-typed client libraries are automatically generated. These client libraries are re-built together with your backend module.

To start sending requests to the backend API from Android, use code similar to the following:


class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
    private static MyApi myApiService = null;
    private Context context;

    @Override
    protected String doInBackground(Pair<Context, String>... params) {
        if(myApiService == null) {  // Only do this once
            MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
                    new AndroidJsonFactory(), null)
                // options for running against local devappserver
                // - 10.0.2.2 is localhost's IP address in Android emulator
                // - turn off compression when running against local devappserver
                .setRootUrl("http://10.0.2.2:8080/_ah/api/")
                .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
                    @Override
                    public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
                        abstractGoogleClientRequest.setDisableGZipContent(true);
                    }
                });
                // end options for devappserver

            myApiService = builder.build();
        }

        context = params[0].first;
        String name = params[0].second;

        try {
            return myApiService.sayHi(name).execute().getData();
        } catch (IOException e) {
            return e.getMessage();
        }
    }

    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(context, result, Toast.LENGTH_LONG).show();
    }
}

The above snippet shows how to create an AsyncTask which makes the request to the backend and prints the incoming result string to a toast in a given context.

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

new EndpointsAsyncTask().execute(new Pair<Context, String>(this, "Manfred"));

Testing your app in an emulator

If you have granted the internet access permission in your AndroidManifest.xml file, added compile dependencies to your Android app's build.gradle file, and added an EndpointsAsyncTask invokation to one of your Android app activities as shown above, you can now test your app and backend locally.

  1. Launch your backend locally as described in Debugging the backend locally and ensure you can access it at http://localhost:8080.
  2. Change the run configuration back to your Android app and run the Android emulator.

Android emulator running in Android Studio

Deploying the backend 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 to App Engine

  3. In the Deploy to App Engine dialog, select your module.

  4. In the Deploy To menu, select the ID of your Cloud Platform project. If you are running this task for the first time, you are prompted to first sign-in with your Google Account.
  5. Update your src/main/webapp/WEB-INF/appengine-web.xml file's <application> property by replacing myApplicationId with the ID of your Cloud Platform project.
  6. Click Deploy. You can monitor the status of your deployment in the Android Studio console.

Testing against a deployed backend

Once you have deployed your backend to App Engine, connect your Android app to it by modifying EndpointsAsyncTask class. Replace these lines:

MyApi.Builder builder = new MyApi.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:

MyApi.Builder builder = new MyApi.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.

You can now run your Android app in an emulator or on the physical device, and successfully communicate with your new App Engine backend!

Cleanup

To avoid incurring charges to your Google Cloud Platform account for the resources used in this tutorial:

  1. Go to the Cloud Platform Console.
  2. In the list of projects, select the project that you want to shut down.
  3. In the prompt, type your project ID to confirm the deletion.
  4. Click Shut down to schedule your project for deletion.

What's next

Send feedback about...

App Engine standard environment for Java