在Android中以编程方式检查是否已设置至少一个帐户

时间:2018-09-10 18:18:02

标签: android accountmanager

我一直在尝试确定是否在Android设备中设置了任何帐户。

我尝试了以下代码,但返回空列表。有没有办法找出是否已在Android中设置帐户?

AccountManager accountManager = AccountManager.get(applicationContext);
Account[] accounts = accountManager.getAccounts()

我已在android清单文件中设置了所需的权限。

<uses-permission android:name="android.permission.GET_ACCOUNTS"/>

1 个答案:

答案 0 :(得分:1)

如果您的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;