Implementazione di Android

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

Configurare Google Play Services

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

Ottenere un ID istanza

La seguente riga di codice restituisce un ID istanza:

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

Generare un token

Per generare token è necessario un ID progetto generato dalla 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);

Gestire i token e gli ID istanza

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

Eliminare token e ID istanza

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

Puoi anche eliminare l'ID istanza stesso, 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();

Token di aggiornamento

Il servizio ID istanza avvia periodicamente i callback (ad esempio, ogni 6 mesi), richiedendo alla tua app di aggiornare i token. Può anche avviare richiamate quando:

  • Si sono verificati problemi di sicurezza, ad esempio problemi SSL o della piattaforma.
  • Le informazioni sul dispositivo non sono più valide, ad esempio backup e ripristino.
  • Il servizio ID istanza è interessato.

Implementa il servizio di listener 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>