用这样的 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";
这些代表您的应用程序向用户请求的权限。此示例中请求的范围记录在此处: