首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Android: AccountManager.getAccounts()返回一个空数组

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

Stack Overflow用户
提问于 2016-01-28 08:00:32
回答 3查看 14K关注 0票数 16

我正在写一个针对棒棒糖和更高版本的应用程序。这是我的第一个Android应用。

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

代码语言:javascript
运行
复制
public void getAllContactsAccounts(Context context){
    AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
    Account[] accounts = accountManager.getAccounts();
    System.out.println("PrintingAccounts: " + accounts.length);
    for(Account a : accounts){
        System.err.println("AccountName: " + a.name);
    }
}

中的数组accountManager.getAccounts()结果长度为0,什么也不会发生。

我想不出怎么解决这个问题。我已经添加了必要的权限(加上一些其他权限),没有发生安全异常,应用程序运行良好,但它似乎就是无法检索帐户。

对我在这里能做些什么有什么建议吗?

EN

Stack Overflow用户

发布于 2016-08-24 09:20:10

由于SdkTarget 23及更高版本(棉花糖6.0),您需要向用户请求通过运行时访问的权限

代码语言:javascript
运行
复制
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()中的代码段仅供参考

这里是这些更改的参考和一些Documentation

票数 7
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35050548

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档