【问题标题】:Can't get default account in OREO无法在OREO中获取默认帐户
【发布时间】:2018-12-09 21:56:48
【问题描述】:
在 Android Oreo 中,AccountManager.getAccountsByType("com.google"); 返回 null。
它在 Android 8 以下版本中运行良好。
下面是我的代码:
private static Account getAccount(AccountManager accManager) {
Account[] accounts = accManager.getAccountsByType("com.google");
Account account;
if (accounts.length > 0) {
account = accounts[0];
} else {
account = null;
}
return account;
}
提前致谢。
【问题讨论】:
标签:
android
accountmanager
android-8.0-oreo
【解决方案1】:
根据 Android 的更新,从 Oreo 开始,我们不能使用 AccountManager.getAccountsByType 来获取用户设备上配置的 google 帐户列表,因为他们已经更新了 Google 登录功能。新功能将提示用户选择帐户,并且该帐户仅对我们的应用可见。
查看文档:https://developer.android.com/about/versions/oreo/android-8.0-changes#aaad
如果您仍想继续向用户显示所有帐户的旧方法,则需要通过执行以下步骤获得用户的额外同意。
您可以使用GoogleAuthUtil.requestGoogleAccountsAccess 获取 Google 帐户列表。
示例代码如下:
new Thread(() -> {
try {
GoogleAuthUtil.requestGoogleAccountsAccess(getApplicationContext());
} catch (Exception e) {
if (e instanceof UserRecoverableAuthException) {
startActivityForResult(((UserRecoverableAuthException) e).getIntent(),
REQ_CODE_PERMISSION_GET_GOOGLE_ACCOUNTS);
} else {
Log.e("SignIn", "Exception in getting google accounts" + e);
}
}
}).start();
这将创建一个活动来提示用户接受同意以允许 Google Play 服务访问设备上配置的 google 帐户列表。
然后您可以在您的活动上覆盖onActivityResult() 函数以在之后继续。
然后你就可以像之前一样使用AccountManager.getAccountsByType获取谷歌账户列表了。
编码愉快!