Android Implementation

The following examples will help you implement Instance ID in an Android client. Note that these examples use the GCM scope, which you would use to manage tokens in Android client for Google Cloud Messaging.

Set Up Google Play Services

To write your client application, use the Google Play services SDK, as described in Set up Google Play Services SDK. The Play Services Library includes the Instance ID library.

Get an Instance ID

The following line of code returns an Instance ID:

String iid = InstanceID.getInstance(context).getId();

Generate a token

Generating tokens requires a Project ID generated by the Google Developers Console.

String authorizedEntity = PROJECT_ID; // Project id from Google Developer Console
String scope = "GCM"; // e.g. communicating using GCM, but you can use any
                      // URL-safe characters up to a maximum of 1000, or
                      // you can also leave it blank.
String token = InstanceID.getInstance(context).getToken(authorizedEntity,scope);

Manage tokens and Instance IDs

Instance ID lets you delete and refresh tokens.

Delete tokens and Instance IDs

String authorizedEntity = PROJECT_ID;
String scope = "GCM";

You can also delete the Instance ID itself, including all associated tokens. The next time you call getInstance() you will get a new Instance ID:

String newIID = InstanceID.getInstance(context).getId();

Refresh tokens

The Instance ID service initiates callbacks periodically (for example, every 6 months), requesting that your app refreshes its tokens. It may also initiate callbacks when:

  • There are security issues; for example, SSL or platform issues.
  • Device information is no longer valid; for example, backup and restore.
  • The Instance ID service is otherwise affected.

Implement the Instance ID listener service in your app to receive these callbacks:

public class MyInstanceIDService extends InstanceIDListenerService {
  public void onTokenRefresh() {

  private void refreshAllTokens() {
    // assuming you have defined TokenList as
    // some generalized store for your tokens
    ArrayList<TokenList> tokenList = TokensList.get();
    InstanceID iid = InstanceID.getInstance(this);
    for(tokenItem : tokenList) {
      tokenItem.token =
      // send this tokenItem.token to your server

You must also configure this service in the Manifest file for the project:

<service android:name=".MyInstanceIDService" android:exported="false">
        <action android:name=""/>

Enviar comentarios sobre…