Если ваш уровень API равен 23 (или выше), я думаю, вам нужно будет запросить разрешение во время выполнения, попробуйте следующее:
if(ContextCompat.checkSelfPermission(this, Manifest.permission. GET_ACCOUNTS) == getPackageManager().PERMISSION_GRANTED)
{
// permission granted, get the accounts here
accountManager = AccountManager.get(applicationContext);
Account[] accounts = accountManager.getAccounts()
}
else
{
// permission not granted, ask for it:
// if user needs explanation , explain that you need this permission (I used an alert dialog here)
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.GET_ACCOUNTS)) {
new AlertDialog.Builder(this)
.setTitle("Permission Needed")
.setMessage("App needs permission to read your accounts ... etc")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.GET_ACCOUNTS}, GET_ACCOUNTS_PERMISSION);
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create().show();
}
// no explanation needed, request the permission
else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.GET_ACCOUNTS}, GET_ACCOUNTS_PERMISSION);
}
}
А затем переопределите этот метод для обработки ответа пользователя
// this function is triggered whenever the application is asked for permission and the user made a choice
// it check user's response and do what's needed.
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == GET_ACCOUNTS_PERMISSION) {
// check if user granted or denied the permission:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
// permission was granted , do the work related to account here:
accountManager = AccountManager.get(applicationContext);
Account[] accounts = accountManager.getAccounts()
}
else
{
//permission denied, what do you want to do?
}
}
}
и вам нужно определить GET_ACCOUNTS_PERMISSION
в классе (не внутри методов), это константа, чтобы вы знали, какое разрешение запрашивается, вы можете заменить его на любое имя или значение, какое захотите.также определите accountManager, чтобы он был доступен из обоих методов.
int GET_ACCOUNTS_PERMISSION = 0;
AccountManager accountManager;