Android AccountManager.getUserData() returns null

ⅰ亾dé卋堺 提交于 2019-12-01 21:55:06

There is a much simpler solution:

Don't add the user-data with addAccountExplicitly(Account, String, Bundle). Instead, just pass an empty bundle and use setUserData(Account, String, String) to add the user-data after you created the account with addAccountExplicitly.

It may be a little less convenient, but it will make sure that the user-data cache is populated properly and won't return null.

After some testing I've found these issues.

  • The problem only occurs on the account created after an account was manually deleted through accounts in Settings.
  • Restarting the device or reinstalling the app fixes the issue (until the first point happens again).
  • So far I have only seen the issue on a HTC

The solution:

Call the below method in addAccount() of your Authenticator.

/**
 * This method is a hack to fix a bug that is found on HTC devices.
 *
 * The issue is basically when ever an account is manually deleted through the devices
 * settings the user data that is saved in the next account that is created is not accessible.
 * The solution is to create a temp account and delete it from the app instead. Deleting
 * accounts via the AccountManager gets around the bug.
 */
private void htcAccountSyncHack() {
    Context appContext = [Application].getInstance();
    Account account = new Account([accountName], [accountType]);
    AccountManager accountManager = (AccountManager) appContext.getSystemService(
            Context.ACCOUNT_SERVICE);
    accountManager.addAccountExplicitly(account, null, null);
    accountManager.removeAccount(account, null, null);
    SharedprefsMgr.setBooleanOnSessionSets(SharedprefsMgr.ACCOUNT_MANUALLY_DELETED, false);
}

Ideally you will have a ContentProvider that is registered as a OnAccountsUpdateListener in AccountManager. You can then use this to work out if the account was manually deleted or not. If it wasn't there is no need to call this method every time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!