Google App Engine

Using Endpoints in an Android Client

Generating the client library from the backend API

Your Android client requires the client library generated from the backend API your client is using. So, if you don't have this yet, generate the client library. We'll show you where to add this to the Android client project later.

Setting up the project

In these instructions, we will be using Android Studio. If you haven't already done so, you'll need to set up Android Studio to support an Endpoints client. This is covered in the Android client tutorial section Installing Android SDKs and required packages in Android Studio.

Configuring the project

In Android Studio, your project uses the build.gradle file for dependencies and other settings. This file is located in your project src directory. You need to configure this file to support your client.

To configure build.gradle:

  1. Double-click build.gradle to open it.

  2. Edit this file so it contains the following lines:

    buildscript {
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:0.6.+'
        }
    }
    apply plugin: 'android'
    
    repositories {
       maven {
            url 'http://google-api-client-libraries.appspot.com/mavenrepo'
        }
        mavenCentral()
        mavenLocal()
    }
    
    android {
        compileSdkVersion 19
        buildToolsVersion "19.0.0"
    
        defaultConfig {
            minSdkVersion 8
            targetSdkVersion 19
        }
    }
    
    dependencies {
        compile 'com.android.support:support-v4:18.0.+'
    
        // BEGIN Google APIs
    
        // Play Services will validate the application prior to allowing OAuth2 access.
        compile(group: 'com.google.android.gms', name: 'play-services', version: '4.0.30')
    
        // The following lines implement maven imports as defined at:
        // https://code.google.com/p/google-api-java-client/wiki/Setup
    
        // Add the Google API client library.
        compile(group: 'com.google.api-client', name: 'google-api-client', version: '1.17.0-rc') {
            // Exclude artifacts that the Android SDK/Runtime provides.
            exclude(group: 'xpp3', module: 'xpp3')
            exclude(group: 'org.apache.httpcomponents', module: 'httpclient')
            exclude(group: 'junit', module: 'junit')
            exclude(group: 'com.google.android', module: 'android')
        }
    
        // Add the Android extensions for the Google API client library.
        // This will automatically include play services as long as you have download that library
        // from the Android SDK manager.
        // Add the Android extensions for the Google API client library.
        compile(group: 'com.google.api-client', name: 'google-api-client-android',
                version: '1.17.0-rc')
        {
            // Exclude play services, since we're not using this yet.
            exclude(group: 'com.google.android.google-play-services', module: 'google-play-services')
        }
    
        // END Google APIs
    
    
        // The following client libraries make HTTP/JSON on Android easier.
    
        // Android extensions for Google HTTP Client.
        compile(group: 'com.google.http-client', name: 'google-http-client-android',
                version: '1.17.0-rc') {
            exclude(group: 'com.google.android', module: 'android')
        }
    
        // This is used by the Google HTTP client library.
        compile(group: 'com.google.guava', name: 'guava', version: '14.0.+')
    
    }
    
  3. Click File > Save All and then exit Android Studio and restart it.

Adding the client library to the project

To add the client library to the Android project:

  1. Add a /libs directory to your project if it doesn't already have one. It should be a peer to the /src directory.

  2. Copy the client library generated from the backend API into /libs.

  3. Select the library you just added, right-click, then select Add As Library to your project.

Creating the service object

In your project code, you must use a service object to make requests to the backend API. For unauthenticated requests, construct the service object as follows:

Tictactoe.Builder builder = new Tictactoe.Builder(
  AndroidHttp.newCompatibleTransport(), new GsonFactory(), null);
service = builder.build();

replacing the name Tictactoe with the name of your backend API.

Calling the backend API

In your project, call the API using the service object. For example:

ScoreCollection scores = service.scores().list().execute();

In the snippet above, we are requesting a list of all Score objects on the server. If list required parameters, or a request body, you would provide them in the invocation. Android Studio provides code completion to identity available method calls, and their required parameters.

It is important to note that because API calls result in requests over the network, you are required to make requests in their own thread. (This requirement was added to recent versions of Android, but it is a best practice even in older versions.) To do this, you use a Thread or AsyncTask. For example:

private class QueryScoresTask extends AsyncTask<Void, Void, ScoreCollection>{
  Context context;

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

  protected Scores doInBackground(Void... unused) {
    ScoreCollection scores = null;
    try {
      scores = service.scores().list().execute();
    } catch (IOException e) {
      Log.d("TicTacToe", e.getMessage(), e);
    }
    return scores;
  }

  protected void onPostExecute(ScoreCollection scores) {
    // Do something with the result.
  }
}

Making authenticated calls

These instructions cover only the client coding you need to add. They assume that you have already added the Endpoints support for auth as described in Adding Authentication to Endpoints.

If your Android client is making calls to an Endpoint that requires authentication, you must:

Configuring Your Android client to provide credentials

To support requests to an Endpoint that requires authentication, your Android client needs to get user credentials and pass them to the service object.

Getting the user credentials and using the account picker requires you to have the following Android permissions:

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

To get the user credentials, you call GoogleAccountCredential.usingAudience as follows:

// Inside your Activity class onCreate method
settings = getSharedPreferences(
   "TicTacToeSample", 0);
credential = GoogleAccountCredential.usingAudience(this,
   "server:client_id:1-web-app.apps.googleusercontent.com");

where the second parameter to the call is the prefix server:client_id prepended to the web client ID of the backend API.

Sample code: getting credentials for the service object

The following code shows how to get credentials and pass it to the service object:

// Inside your Activity class onCreate method
settings = getSharedPreferences("TicTacToeSample", 0);
credential = GoogleAccountCredential.usingAudience(this,
   "server:client_id:1-web-app.apps.googleusercontent.com");
setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));

Tictactoe.Builder builder = new Tictactoe.Builder(
   AndroidHttp.newCompatibleTransport(), new GsonFactory(),
   credential);
service = builder.build();

if (credential.getSelectedAccountName() != null) {
 // Already signed in, begin app!
} else {
 // Not signed in, show login window or request an account.
}

// setSelectedAccountName definition
private void setSelectedAccountName(String accountName) {
 SharedPreferences.Editor editor = settings.edit();
 editor.putString(PREF_ACCOUNT_NAME, accountName);
 editor.commit();
 credential.setSelectedAccountName(accountName);
 this.accountName = accountName;
}

The above sample code looks up any shared preferences stored by the Android app and attempts to find the name of the account the user would like to use to authenticate to your application. If successful, the code creates a credentials object and passes it into your service object. These credentials allow your Android application to pass the appropriate token to your backend.

Notice that the code sample checks to see whether or not the Android app already knows which account to use. If it does, the logical flow can continue on and run the Android app. If the app doesn't know which account to use, the app should display a login screen or prompt the user to pick an account.

Finally, the sample creates a credentials object and passes it into the service object. These credentials allow your Android application to pass the appropriate token to your App Engine web app.

Using the account picker

Android provides an intent to select a user account. You can invoke this as follows:

static final int REQUEST_ACCOUNT_PICKER = 2;

void chooseAccount() {
  startActivityForResult(credential.newChooseAccountIntent(),
    REQUEST_ACCOUNT_PICKER);
}

A handler for interpreting the result of this intent is shown here:

@Override
protected void onActivityResult(int requestCode, int resultCode,
   Intent data) {
 super.onActivityResult(requestCode, resultCode, data);
 switch (requestCode) {
   case REQUEST_ACCOUNT_PICKER:
     if (data != null && data.getExtras() != null) {
       String accountName =
           data.getExtras().getString(
               AccountManager.KEY_ACCOUNT_NAME);
       if (accountName != null) {
         setSelectedAccountName(accountName);
         SharedPreferences.Editor editor = settings.edit();
         editor.putString(PREF_ACCOUNT_NAME, accountName);
         editor.commit();
         // User is authorized.
       }
     }
     break;
 }
}

Testing an Android client against a local development server

You can test your client against a backend API running in production App Engine at any time without making any changes. However, if you want to test your client against a backend API running on the local development server, you'll need to change one line of code in the client to point to the IP address of the machine running the local development server.

To make the required changes and test using the local dev server:

  1. Note the IP address of the machine that is running the local dev server: you need it when you add code to the Android client.

  2. Start the local development server, as described in Running and testing API backends locally. You may need to specify the address 0.0.0.0 as described at that link.

  3. In your Android Studio client project, locate the code that gets the handle to the backend API service; typically, this code will use a Builder to set up the API request.

  4. Override the root URL on the Builder object (this is the URL the Android client connects to in the backend API call) by adding the line:

    yourBuilderObject.setRootUrl("http://<your-machine-IP-address>:8080/_ah/api");
    

    For example:

    public static Helloworld getApiServiceHandle(@Nullable GoogleAccountCredential credential) {
        // Use a builder to help formulate the API request.
        Helloworld.Builder helloWorld = new Helloworld.Builder(AppConstants.HTTP_TRANSPORT,
                AppConstants.JSON_FACTORY,credential);
    
        helloWorld.setRootUrl("http://<your-machine-IP-address>:8080/_ah/api");
        return helloWorld.build();
    }
    

    Be sure to replace <your-machine-IP-address> with your system's actual IP value.

  5. Rebuild your Android client project.

  6. If you want to run your client app on an AVD emulator:

    1. In Android Studio, select Tools > Android > AVD Manager and start an existing AVD if you have one, otherwise create one first and start it.
    2. Select Run > Debug <your-project-name>.
    3. Select your AVD when prompted to choose a device.
    4. Test your client as desired.
  7. If you want to run your client app on a physical Android device,

    1. Make sure your Android device is enabled for debugging.
    2. In Android Studio, select Run > Debug <your-project-name>.
    3. Select your physical Android device when prompted to choose a device.
    4. Test your client as desired.

Sample client source code

For a complete sample client that illustrates the concepts described above, see the Android client tutorial.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.