我目前正在尝试为我的项目实施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
,这是刷新令牌的方法。
谢谢你的帮助。
答案 0 :(得分:0)
AccountManager accountManager=AccountManager.get(getContext());
String oAuth=accountManager.peekAuthToken(account,"oauth");
accountManager.getAuthToken(accounts [0],AUTHENTICATION_TOKEN_TYPE,null,false,null,null);
已弃用