我正在写一个针对棒棒糖和更高版本的应用程序。这是我的第一个Android应用。
我正在尝试获取与该设备关联的所有帐户的列表。下面是我的代码:
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,什么也不会发生。
我想不出怎么解决这个问题。我已经添加了必要的权限(加上一些其他权限),没有发生安全异常,应用程序运行良好,但它似乎就是无法检索帐户。
对我在这里能做些什么有什么建议吗?
发布于 2016-08-24 09:20:10
由于SdkTarget 23及更高版本(棉花糖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()中的代码段仅供参考
https://stackoverflow.com/questions/35050548
复制相似问题