Android:AccountManager.getAccounts()返回一个空数组

时间:2016-01-28 00:00:32

标签: android

我正在编写针对Lollipop及以上版本的应用。这是我的第一个Android应用程序。

我正在尝试获取与该设备关联的所有帐户的列表。这是我的代码:

hotfix/2.5.1

来自accountManager.getAccounts()的数组最终长度为0,没有任何反应。

我无法弄清楚如何解决这个问题。我已经添加了必要的权限(加上其他几个),没有发生安全异常,应用程序运行正常,但它似乎无法检索帐户。

关于我在这里可以做什么的任何建议?

3 个答案:

答案 0 :(得分:10)

从Android 8.0开始,GET_ACCOUNTS不再足以访问设备上的帐户。

基于documentation

  

在Android 8.0(API级别26)中,除非身份验证者拥有帐户或用户授予该访问权限,否则应用无法再访问用户帐户。 GET_ACCOUNTS权限不再足够。要授予对帐户的访问权限,应用应使用AccountManager.newChooseAccountIntent()或特定于身份验证器的方法。在访问帐户后,应用程序可以调用AccountManager.getAccounts()来访问它们。

您可以查看此link以了解AccountManager.newChooseAccountIntent()

的使用情况

答案 1 :(得分:6)

自SdkTarget 23及更高版本(Marshmallow 6.0)起,您需要询问用户是否有权通过运行时访问

 int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 0;
    // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.GET_ACCOUNTS)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                android.Manifest.permission.GET_ACCOUNTS)) {

            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.GET_ACCOUNTS},
                    MY_PERMISSIONS_REQUEST_READ_CONTACTS);
    }
}
    String possibleEmail="";
    try{
        possibleEmail += "************* Get Registered Gmail Account *************\n\n";
        Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");

        for (Account account : accounts) {

            possibleEmail += " --> "+account.name+" : "+account.type+" , \n";
            possibleEmail += " \n\n";

        }
    }


     Log.i("EXCEPTION", "mails: " + possibleEmail);

onCreate()中的片段仅供参考

Here's a reference of these changes and some Documentation

答案 2 :(得分:0)

由于某种原因,我也必须请求“ android.permission.READ_CONTACTS”才能访问帐户列表。 似乎需要的权限是:

android.permission.READ_CONTACTS

android.permission.GET_ACCOUNTS