如果已设置至少一个帐户,请在Android中以编程方式检查

问题描述 投票:0回答:1

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

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

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

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

<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
android accountmanager
1个回答
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;
© www.soinside.com 2019 - 2024. All rights reserved.