Tak, tokeny identyfikatorów Google są wydawane na okres jednej godziny i wygasną, możesz po prostu użyć w aplikacji aplikacji silentSignIn, aby uzyskać nową bez żadnej interakcji użytkownika. Jeśli Twój dotychczasowy token nie wygasł, otrzymasz (cofniętą) wersję z powrotem (OptionalPendingResult
zwrócony będzie miał isDone() == true
); jeśli wygasł już, otrzymasz odświeżony (ale potrwa to nieco dłużej, a więc OptionalPendingResult isDone()
zostanie false
).
Oto sample code (wątek UI, patrz uwaga poniżej o wątku roboczego):
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_id))
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
...
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d(TAG, "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result); // result.getSignInAccount().getIdToken(), etc.
} else {
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently. Cross-device
// single sign-on will occur in this branch.
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
@Override
public void onResult(GoogleSignInResult googleSignInResult) {
handleSignInResult(googleSignInResult); // result.getSignInAccount().getIdToken(), etc.
}
});
}
Pamiętaj, czy zadzwonić silentSignIn
w wątku UI lub wątku roboczego. Jeśli wywołasz go w wątku roboczym, spójrz na ten wpis, używając blockingConnect()
+ await()
, co znacznie upraszcza kod: Silent sign in to retrieve token with GoogleApiClient