如果authToken无效,应用程序应该如何反应

时间:2014-08-16 20:55:09

标签: android accountmanager android-syncadapter

在我的项目中,我需要定期连接到服务器。因此,我正在实现一个AccountAuthenticator和SyncAdapter将它们插入到机器人框架中。应用程序必须定期连接,比如说每5或10分钟一次。

无论我是否存储密码或authToken,两者都可能无效,SyncAdapter将无法再同步。从逻辑上讲,需要通知用户。

如果AccountAuthenticator.getAuthToken(..)无法获得新的authToken,我想显示登录表单:

@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response,
                           Account account, String authTokenType,
                           Bundle options) throws NetworkErrorException {
    // code derived from SampleSyncAdapter

    // If the caller requested an authToken type we don't support, then
    // return an error
    if (!authTokenType.equals(Helper.ACCOUNT_TYPE)) {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ERROR_MESSAGE,
                         "invalid authTokenType");
        return result;
    }

    // Extract the username and password from the Account Manager, and ask
    // the server for an appropriate AuthToken.
    final AccountManager am = AccountManager.get(context);
    final String password = am.getPassword(account);
    if (password != null) {
        final LoginData loginData =
                           NetworkUtility.authenticate(account.name, password);

        if (loginData.wasSuccessful() &&
            !TextUtils.isEmpty(loginData.getAuthenticationToken())) {
            final Bundle result = new Bundle();
            result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
            result.putString(AccountManager.KEY_ACCOUNT_TYPE,
                             Helper.ACCOUNT_TYPE);
            result.putString(AccountManager.KEY_AUTHTOKEN,
                             loginData.getAuthenticationToken());
            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 panel.
    final Intent intent = new Intent(context, AuthenticatorActivity.class);
    intent.putExtra(AuthenticatorActivity.PARAM_USERNAME, account.name);
    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,
                    response);
    final Bundle bundle = new Bundle();
    bundle.putParcelable(AccountManager.KEY_INTENT, intent);
    return bundle;
}

但不幸的是,这不起作用,没有创建提示。

我没有找到任何有关最佳做法的信息。我检查了新的CouchSurfing应用程序,他们只是删除了帐户。我现在没有检查,但我认为谷歌会禁用同步。这两种解决方案都不适用于我的用例。

1 个答案:

答案 0 :(得分:0)

解决方案比我想象的简单,谷歌也做到了:

将消息发布到通知区域(http://developer.android.com/guide/topics/ui/notifiers/notifications.html),打开时可以显示登录屏幕。