所以这是我的谷歌ApiClient:
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestServerAuthCode(serverID)
.build();
mGoogleApiClient = new GoogleApiClient.Builder(PSSignInFlowActivity.this)
.enableAutoManage(this/* FragmentActivity */, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
这就是当我按下登录按钮时发生的情况:
public void login(){
Log.i("", "handleSignInResult login:");
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
它把我带到这里:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("", "handleSignInResult onActivityResult:" + requestCode + ".." + resultCode);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
Log.i("","handleSignInResult onActivityResult: " +result.getSignInAccount() + ",,," + result.getStatus());
handleSignInResult(result);
}
}
它称之为:
private void handleSignInResult(GoogleSignInResult result) {
Log.i("", "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
String authCode = acct.getServerAuthCode();
// if(authCode != null)
// storyFragment.setFromGoogle(authCode);
} else {
// Signed out, show unauthenticated UI.
}
}
我的问题是我需要一个来自GoogleSignInResult的accessToken,但我只得到了serverAuthCode。我看到你可以在auth2操场上用serverAuthCode交换访问令牌。这可以通过编程实现吗?
这对我有效:
try{
String scope = "oauth2:" + Scopes.PROFILE;
Account account = new Account(acct.getEmail(), "com.google");
final String token = GoogleAuthUtil.getToken(PSSignInFlowActivity.this, account, scope);
runOnUiThread(new Runnable() {
@Override
public void run() {
storyFragment.setFromGoogle(token);
}
});
}catch (Exception e){
Log.e("","error trying to get client secret : " + e.getMessage());
}