我在使用适用于 Android 的 Google+ Sign 时发现了一个小问题,并且在搜索网络后(很明显)我大声问我的问题,看看是否有人注意到了同样的问题。
我正在按照所述为我的应用启用服务器端 API 访问 here. 让我详细说明一下是怎么回事。拿这个 fragment :
Bundle appActivities = new Bundle();
appActivities.putString(GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES,
"<APP-ACTIVITY1> <APP-ACTIVITY2>");
String scopes = "oauth2:server:client_id:<SERVER-CLIENT-ID>:api_scope:<SCOPE1> <SCOPE2>";
String code = null;
try {
code = GoogleAuthUtil.getToken(
this, // Context context
Plus.AccountApi.getAccountName(mGoogleApiClient), // String accountName
scopes, // String scope
appActivities // Bundle bundle
);
} catch (IOException transientEx) {
// network or server error, the call is expected to succeed if you try again later.
// Don't attempt to call again immediately - the request is likely to
// fail, you'll hit quotas or back-off.
...
return;
} catch (UserRecoverableAuthException e) {
// Requesting an authorization code will always throw
// UserRecoverableAuthException on the first call to GoogleAuthUtil.getToken
// because the user must consent to offline access to their data. After
// consent is granted control is returned to your activity in onActivityResult
// and the second call to GoogleAuthUtil.getToken will succeed.
startActivityForResult(e.getIntent(), AUTH_CODE_REQUEST_CODE);
return;
} catch (GoogleAuthException authEx) {
// Failure. The call is not expected to ever succeed so it should not be
// retried.
...
return;
} catch (Exception e) {
throw new RuntimeException(e);
}
看到 UserRecoverableAuthException
及其注释了吗?嗯,这就是我想跟你谈的。在这种情况下,如您所见,另一个 Activity 将启动,并开始一个流程,您必须接受应用程序请求的权限。如您所见,正在使用 startActivityForResult
方法。我观察到的是,当用户接受授予权限时返回 Activity.RESULT_OK
但当发生错误/崩溃或用户时返回 Activity.RESULT_CANCELED
只是拒绝给予许可并取消流程。
所以这是(是的,最后!)我的问题......我如何区分一种情况(错误/崩溃)与另一种情况(可能的用户流)?
最佳答案
好吧,经过一段时间的努力,我想我找到了解决方案。我不知道这样做是否正确,但我认为我应该分享它,所以就这样吧。
我们有 onActivityresult
方法,执行登录/登录的 Activity 应该实现。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
(...)
}
我的想法(经过一段时间的思考,后来证实)是 Intent data
参数应该有某种线索或信息,说明返回的是哪种错误或结果。稍作检查后,我发现在用户拒绝应用程序权限的情况下,此 Intent 有一个带有键 Error
和值 UserCancel
的额外字符串。所以这就是我最终用来区分一个案例和另一个案例的方法。希望对您有所帮助!
data.getExtraString("Error"); // This should have the value "UserCancel" when the user
// refused to give the permissions required by the app.
请注意,data
Intent 可能并不总是提供此 ExtraString,实际上对于 onActityResult
的某些调用可能为 null
,因此在使用它之前,你应该检查 if (data != null)
。
关于android - 适用于 Android 的 Google+ 登录 - Google 权限 Activity 结果代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25184548/