我正在我的 Android 应用程序中运行后台服务。我使用从登录 Activity 中获取的 IdToken 在后端服务器上进行身份验证。该服务以 START_STICKY
模式运行,因此即使应用程序关闭,该服务也会继续在后台运行以从后端服务器获取任何通知。我面临的问题是当 IdToken 过期时,我无法在服务本身中更新它。如果 token 已过期,回调函数不会收到任何结果。如果 token 还没有过期,它会立即得到结果。
这是 signIn 函数和 handleSignIn 函数的代码。
private void signIn() {
new Thread(new Runnable() { public void run() {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestIdToken("<My server_client_id>")
.build();
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(context)
.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);
} 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.
Log.d(TAG, "had to sign in again");
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
@Override
public void onResult(GoogleSignInResult googleSignInResult) {
Log.d(TAG, "got result");
handleSignInResult(googleSignInResult);
}
});
}}}).start();
}
最佳答案
尝试移动
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
@Override
public void onResult(GoogleSignInResult googleSignInResult) {
Log.d(TAG, "got result");
handleSignInResult(googleSignInResult);
}
});
在其 if 语句之前。我知道谷歌文档说要按照你的方式使用它,我也这样做了,直到我意识到如果 ResultCallback 只在 else block 中初始化,在 opr
已经运行之后,它就永远不会被调用.
按照我的建议,你的代码应该是这样的:
private void signIn() {
new Thread(new Runnable() { public void run() {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestIdToken("<My server_client_id>")
.build();
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(context)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn
(mGoogleApiClient);
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
@Override
public void onResult(GoogleSignInResult googleSignInResult) {
Log.d(TAG, "got result");
handleSignInResult(googleSignInResult);
}
});}}).start();
}
关于android - 在 Android 后台服务中静默 Google 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34654482/