我正在尝试遵循Authenticating to OAuth2 Services并实现在 AccountManagerFuture#getResult() 调用提供的 Bundle 中包含 Intent 的部分。
问题是,即使文档说使用 Activity#startActivityForResult(...),我被告知要触发的 Intent 显然是在它自己的任务中开始的,导致 onActivityResult 被立即调用。
我不确定我是否正确执行的另一部分是我启动此 Intent 的方式。因为调用 AccountManager#getAuthToken(...) 的代码隐藏在无法访问当前 Activity 的工作线程中,所以我正在启动一个名为“CredentialsActivity”的新 Activity,然后使用 startActivityForResult 启动操作系统提供的 Intent。
我就是这样做的:
final AccountManagerFuture<Bundle> future = AccountManager.getAuthToken(...);
// Now that we have the Future, we extract the Bundle
Bundle bundle = null;
try {
bundle = future.getResult();
} catch (Exception e) {
log.warn(e, "Got an Exception");
}
if (bundle == null) {
log.info("Unable to get auth token");
return;
}
// Check if the user needs to enter credentials.
final Intent askForPassword = (Intent) bundle.get(AccountManager.KEY_INTENT);
if (askForPassword != null) {
log.dev("Need to prompt for credentials, firing Intent...");
CredentialsActivity.promptForCredentials(context, askForPassword);
}
这些是 CredentialsActivity 的相关部分:
private static final int REQUEST_CODE_LAUNCH_CREDENTIALS_INTENT = 0;
private static Intent newCredentialsActivityIntent(Context context) {
final Intent intent = new Intent(context, CredentialsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
public static void promptForCredentials(Context context, Intent credentialsIntent) {
final Intent intent = newCredentialsActivityIntent(context);
intent.putExtra(Intent.EXTRA_INTENT, credentialsIntent);
context.startActivity(intent);
}
我在 onResume 中触发 Intent:
@Override
protected void onResume() {
super.onResume();
final Intent intent = getIntent();
final Intent credentialsIntent = (Intent) intent.getParcelableExtra(Intent.EXTRA_INTENT);
if (credentialsIntent != null) {
startActivityForResult(credentialsIntent, REQUEST_CODE_LAUNCH_CREDENTIALS_INTENT);
}
}