在我的 android 应用程序中,我试图从 GoogleAuthUtil 获取 AccessToken,如下所示:
accessToken = GoogleAuthUtil.getToken(this, mPlusClient.getAccountName(), "oauth2:" + SCOPES);
但是在这一行我得到如下错误:
E/GoogleAuthUtil(4696): Calling this from your main thread can lead to deadlock and/or ANRs E/GoogleAuthUtil(4696): java.lang.IllegalStateException: calling this from your main thread can lead to deadlock E/GoogleAuthUtil(4696): at com.google.android.gms.auth.GoogleAuthUtil.b(Unknown Source) E/GoogleAuthUtil(4696): at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source) E/GoogleAuthUtil(4696): at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
这个问题有什么解决办法吗?任何帮助将不胜感激。
最佳答案
用这样的 AsyncTask 试试:
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String token = null;
try {
token = GoogleAuthUtil.getToken(
MainActivity.this,
mGoogleApiClient.getAccountName(),
"oauth2:" + SCOPES);
} catch (IOException transientEx) {
// Network or server error, try later
Log.e(TAG, transientEx.toString());
} catch (UserRecoverableAuthException e) {
// Recover (with e.getIntent())
Log.e(TAG, e.toString());
Intent recover = e.getIntent();
startActivityForResult(recover, REQUEST_CODE_TOKEN_AUTH);
} catch (GoogleAuthException authEx) {
// The call is not ever expected to succeed
// assuming you have already verified that
// Google Play services is installed.
Log.e(TAG, authEx.toString());
}
return token;
}
@Override
protected void onPostExecute(String token) {
Log.i(TAG, "Access token retrieved:" + token);
}
};
task.execute();
SCOPES
是 OAuth 2.0 范围字符串的空格分隔列表。例如 SCOPES
可以定义为:
public static final String SCOPES = "https://www.googleapis.com/auth/plus.login "
+ "https://www.googleapis.com/auth/drive.file";
这些代表您的应用向用户请求的权限。此示例中请求的范围记录在此处:
关于android - 来自 GoogleAuthUtil 的 "Calling this from your main thread can lead to deadlock and/or ANRs while getting accesToken"(Android 中的 Google Plus 集成),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17547019/