2015-09-07 110 views
2

我在我的应用程序中使用SyncAdapter和AccountAuthenticator。当做同步的东西时,我调用AccountManager.blockingGetAuthToken来获取访问令牌。我理解这种方法,当它无法获得令牌时(或者换句话说,当getAuthToken方法返回一个Intent来启动Activity时),它会启动我的登录活动。 但它只是返回null,不启动活动。AccountManager.blockingGetAuthToken()不会提示输入凭据

这是我的验证器的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.

+1

我终于通过使用异步方法解决了问题... – KCD

回答

0

看来提问者想通了。

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参数:对于后人,如果你用这个代替它的工作原理。并且文档不正确。