Implementazione di Android

I seguenti esempi ti aiuteranno a implementare l'ID istanza in un client Android. Tieni presente che questi esempi utilizzano l'ambito GCM, che è utile solo a scopo dimostrativo, in quanto Google Cloud Messaging non è più utilizzato.

Configura Google Play Services

Per scrivere la tua applicazione client, utilizza l'SDK Google Play Services, come descritto in Configurare l'SDK Google Play Services. La libreria Play Services include la libreria degli ID istanza.

Recuperare un ID istanza

La seguente riga di codice restituisce un ID istanza:

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

Genera un token

La generazione dei token richiede un ID progetto generato da 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);

Gestisci token e ID istanza

L'ID istanza consente di eliminare e aggiornare i token.

Elimina token e ID istanza

String authorizedEntity = PROJECT_ID;
String scope = "GCM";
InstanceID.getInstance(context).deleteToken(authorizedEntity,scope);

Puoi anche eliminare l'ID istanza, inclusi tutti i token associati. La prossima volta che chiami getInstance(), riceverai un nuovo ID istanza:

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

Aggiorna token

Il servizio ID istanza avvia i callback periodicamente (ad esempio, ogni 6 mesi) richiedendo l'aggiornamento dei token dell'app. Potrebbe anche avviare callback quando:

  • Sono presenti problemi di sicurezza, ad esempio problemi di SSL o della piattaforma.
  • Informazioni del dispositivo non più valide, ad esempio backup e ripristino.
  • L'operazione influisce sul servizio ID istanza.

Implementa il servizio listener di ID istanza nella tua app per ricevere questi callback:

public class MyInstanceIDService extends InstanceIDListenerService {
  public void onTokenRefresh() {
    refreshAllTokens();
  }

  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 =
        iid.getToken(tokenItem.authorizedEntity,tokenItem.scope,tokenItem.options);
      // send this tokenItem.token to your server
    }
  }
};

Devi anche configurare questo servizio nel file manifest del progetto:

<service android:name=".MyInstanceIDService" android:exported="false">
  <intent-filter>
        <action android:name="com.google.android.gms.iid.InstanceID"/>
  </intent-filter>
</service>