Android帐户管理器的getAuthToken返回空值

tktrz96b  于 2022-11-20  发布在  Android
关注(0)|答案(1)|浏览(242)

我目前正在尝试在我的项目中实现AccountManager。创建帐户工作正常,我可以毫无问题地访问 AuthToken
然而,一旦我刷新并更新了AccountManager中的 AuthToken,我似乎就再也无法访问它了,因为AccountManager.getAuthToken()每次都返回null,而且每次我试图访问它时都要刷新令牌。
下面是我的getAuthToken()方法:

public static String getAuthToken(final Context context)
{
    Log.d(TAG, "getAuthToken");
    AccountManager accountManager = AccountManager.get(context);
    String accountType = context.getResources().getString(R.string.account_type);
    Account accounts[] = accountManager.getAccountsByType(accountType);

    if (accounts.length == 0) {
        return null;
    }

    /* This method retrieves the token for the given account but doesn't pop the Authentication Page if not found */
    AccountManagerFuture<Bundle> futureBundle = accountManager.getAuthToken(accounts[0], AUTHENTICATION_TOKEN_TYPE, null, false, null, null);
    Bundle bundle;
    try {
        bundle = futureBundle.getResult();
    } catch (OperationCanceledException ex) {
        Log.wtf(TAG, "operation canceled: " + ex.getMessage());

        return null;
    } catch (IOException ex) {
        Log.wtf(TAG, "IOException: " + ex.getMessage());

        return null;
    } catch (AuthenticatorException ex) {
        throw new RuntimeException(ex.getMessage());
    }

    Log.d(TAG, "AccountManagerUtility getAuthToken: " + bundle.getString(AccountManager.KEY_AUTHTOKEN));
    return bundle.getString(AccountManager.KEY_AUTHTOKEN);
}

下面是更新AccountManager的方法:

public static void updateAccount(Context context, final OAuthToken authToken)
{
    AccountManager accountManager = AccountManager.get(context);
    String accountType = context.getResources().getString(R.string.account_type);
    Account accounts[] = accountManager.getAccountsByType(accountType);
    if (accounts.length == 0) {
        return;
    }

    accountManager.setAuthToken(accounts[0], AUTHENTICATION_TOKEN_TYPE, authToken.getAccessToken());
    accountManager.setPassword(accounts[0], authToken.getRefreshToken());

    final long timestamp = java.lang.System.currentTimeMillis();
    setRefreshTokenTimestamp(context, timestamp); // Updates User data
}

权限是在AndroidManifest

<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.USE_CREDENTIALS"/>
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS"/>

也定义了Authenticator,实际上,在调用了updateAccount之后,Authenticator的getAuthToken也被调用了,这就是刷新令牌的方法.
谢谢你的帮助。

smdncfj3

smdncfj31#

使用此代码从您的应用程序帐户获取AuthToken:

AccountManager accountManager=AccountManager.get(getContext());
    String     oAuth=accountManager.peekAuthToken(account,"oauth");

accountManager.getAuthToken(accounts[0], AUTHENTICATION_TOKEN_TYPE, null, false, null, null);
现在已被取代。

相关问题