在 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 的更新,从 Oreo 开始,我们不能使用 AccountManager.getAccountsByType
获取用户设备上配置的谷歌帐户列表,因为他们已经更新了 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();
这将创建一个 Activity 来提示用户同意允许 Google Play 服务访问设备上配置的谷歌帐户列表。
然后您可以重写 Activity 上的 onActivityResult()
函数以继续。
然后您可以像以前一样使用 AccountManager.getAccountsByType
获取 Google 帐户列表。
编码愉快!
关于android - 无法在 OREO 中获取默认帐户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49169680/