AccountManager getAccount 在Android O 8.0版本中获取为 null ?

版权声明:给别人一份尊重,留自己一方安心。 https://blog.csdn.net/Zheng548/article/details/79689425

问题

  AccountManager accountManager = AccountManager.get(this);
  Account[] accounts = accountManager.getAccounts();

以上代码在 Android 8.0 (API 26) 之前运行地很好,能够获取到 account 信息。但是在最新版本 8.0 上却获取不到,返回 accounts 为 null.

另外,在 Why do I get null from retrieving the user’s gmail?
也是类似的问题。

原因

后来知道,这是 Android 8.0 的 行为变更。

Account access and discoverability
In Android 8.0 (API level 26), apps can no longer get access to user accounts unless the authenticator owns the accounts or the user grants that access. The GET_ACCOUNTS permission is no longer sufficient. To be granted access to an account, apps should either use AccountManager.newChooseAccountIntent() or an authenticator-specific method. After getting access to accounts, an app can can call AccountManager.getAccounts() to access them.
Android 8.0 deprecates LOGIN_ACCOUNTS_CHANGED_ACTION. Apps should instead use addOnAccountsUpdatedListener() to get updates about accounts during runtime.
For information about new APIs and methods added for account access and discoverability, see Account Access and Discoverability in the New APIs section of this document

除非身份验证器拥有用户帐号或用户授予访问权限,否则,应用将无法再访问用户帐号。仅拥有 GET_ACCOUNTS 权限尚不足以访问用户帐号。要获得帐号访问权限,应用应使用 AccountManager.newChooseAccountIntent() 或特定于身份验证器的函数。获得帐号访问权限后,应用可以调用 AccountManager.getAccounts() 来访问帐号。

Android 8.0 已弃用 LOGIN_ACCOUNTS_CHANGED_ACTION。相反,应用在运行时应使用 addOnAccountsUpdatedListener() 获取帐号更新信息。

有关新增 API 和增加的帐号访问和可检测性函数的信息,请参阅此文档的“新增 API”部分中的帐号访问和可检测性。

另外可参考,下面这篇文章
android 8.0 —AccountManager之行为变更

解决

根据文档,

要获得帐号访问权限,应用应使用 AccountManager.newChooseAccountIntent() 或特定于身份验证器的函数。获得帐号访问权限后,应用可以调用 AccountManager.getAccounts() 来访问帐号。

于是

Intent googlePicker = AccountManager.newChooseAccountIntent(null, null,
                new String[] { "com.google"}, true, null, null, null, null);
startActivityForResult(googlePicker, PICK_ACCOUNT_REQUEST);

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        if (requestCode == PICK_ACCOUNT_REQUEST && resultCode == RESULT_OK) {
            String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
            Log.d(TAG, "Account Name=" + accountName);
            String accountType = data.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE);
            Log.d(TAG, "Account type=" + accountType);

            AccountManager accountManager = AccountManager.get(this);
            Account[] accounts = accountManager.getAccounts();
            for (Account a : accounts) {
                Log.d(TAG, "type--- " + a.type + " ---- name---- " + a.name);
            }
        }
    }

问题可以得到解决。
这里写图片描述

猜你喜欢

转载自blog.csdn.net/Zheng548/article/details/79689425