使用CountdownLatch从accountmanager获取Auth令牌

时间:2015-06-24 17:49:37

标签: java android account accountmanager countdownlatch

在向服务器发出请求之前,我正试图从Android帐户中获取身份验证令牌。我试图用CountdownLatch控制流程,以便等到:

  • a)超时(10秒)
  • b)我们得到令牌

    private CountDownLatch tokenLatch = new CountDownLatch(1);
    final long tokenTimeoutSeconds = 10;
    AccountManager manager = AccountManager.get(mContext);
    Account userAccount = getCurrentAccount();
    // Get the auth token
    if (userAccount != null) {
        AccountManagerFuture<Bundle> future = manager.getAuthToken(userAccount, AccountUtility.AUTHTOKEN_TYPE_FULL_ACCESS, true, new AccountManagerCallback<Bundle>() {
            @Override
            public void run(AccountManagerFuture<Bundle> future) {
                try {
                    Bundle bundle = future.getResult();
                    currentAuthToken = bundle.get(AccountManager.KEY_AUTHTOKEN).toString();
                    tokenLatch.countDown();
                } catch (Exception e) {
                    Log.e(LOG_TAG, "Problem getting auth token!", e);
                }
            }
        }, null);
    
        try {
            tokenLatch.await(tokenTimeoutSeconds, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Log.e(LOG_TAG, "Interupted while getting auth token!", e);
        }
    

传递了上下文:

mContext = ...  getApplicationContext();

现在它在这两种情况之前退出。但是,在完成所有其他进程后,它始终会到达AccountManagerCallback。奇怪。我肯定做错了什么。 感谢helperooni!

1 个答案:

答案 0 :(得分:2)

此解释假设已发布的代码在主线程上运行。因为对getAuthToken()的调用中的Handler参数为null,所以回调也将在主线程上运行。这是一个僵局。在调用getAuthToken()之后,主线程阻塞了latch await()。回调无法运行,因为主线程被阻止。锁存器永远不会倒数到零,因为回调无法运行。

发布的代码at this blog提供了一个示例,说明如何在主线程上无阻塞地获取身份验证令牌。