在我的Android应用程序中,我试图从GoogleAuthUtil获取AccessToken,如下所示:
但是在这一行,我得到如下错误:
这个问题有什么解决办法吗?任何帮助将不胜感激。
最佳答案
像这样使用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";
这些代表您的应用向用户请求的权限。此示例中要求的范围记录在这里: