我在我的应用中使用了SyncAdapter和AccountAuthenticator。在进行同步时,我调用AccountManager.blockingGetAuthToken来获取访问令牌。我理解这种方法的方式是,当它无法获取令牌时(或者换句话说,当getAuthToken方法返回一个Intent来启动Activity时)它启动我的登录活动。 但它只返回null,而不启动Activity。
这是我的身份验证器的getAuthToken方法。
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
// Extract the username and password from the Account Manager, and ask
// the server for an appropriate AuthToken.
final AccountManager am = AccountManager.get(mContext);
String authToken = am.peekAuthToken(account, authTokenType);
// Lets give another try to authenticate the user
if (TextUtils.isEmpty(authToken)) {
final String password = am.getPassword(account);
if (password != null) {
try {
authToken = APIHelper.getInstance().logIn(account.name, password);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// If we get an authToken - we return it
if (!TextUtils.isEmpty(authToken)) {
// cache
am.setAuthToken(account, authTokenType, authToken);
final Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
return result;
}
// If we get here, then we couldn't access the user's password - so we
// need to re-prompt them for their credentials. We do that by creating
// an intent to display our AuthenticatorActivity.
final Intent intent = new Intent(mContext, AuthActivity.class);
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
intent.putExtra(AuthActivity.ARG_ACCOUNT_TYPE, account.type);
intent.putExtra(AuthActivity.ARG_AUTH_TYPE, authTokenType);
final Bundle bundle = new Bundle();
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
return bundle;
}
顺便说一下,大部分代码来自 this blog.
答案 0 :(得分:1)
似乎提问者想出来了。对于子孙后代,如果您使用它,它会起作用:
AccountManagerFuture<Bundle> resultFuture = accountManager.getAuthToken(
account,
AUTH_TOKEN_TYPE,
null,
activity,
null,
null
);
Bundle bundle = resultFuture.getResult();
return bundle.getString(AccountManager.KEY_AUTHTOKEN);
我猜blockingGetAuthToken()
无法自动执行此操作,因为它缺少activity
参数。文档不正确。