检测用户是否拒绝或授予应用程序权限,然后处理一些代码

Detect if user denied or granted permission to an app and then process some code

我的应用程序需要读取 external storage 的权限,我在 OnCreate 方法中有代码来自检权限是否已被授予,如果没有向用户请求,我的问题是该应用程序知道用户的选择...如果用户拒绝它,则应调用 activity.finishaffinity 否则该应用程序应继续 运行... 这是我到目前为止的代码....

class MyActivity:AppCompatActivity{
    protected override void OnCreate(Bundle savedInstanceState){
        checkpermission();
        }
      private void checkpermission(){
         if(ContextCompat.CheckSelfPermission(this,Manifest.Permission.ReadExternalStorage)
         !=Permission.Granted){
         //Permission is not granted so request one
          RequestPermisions(new string[]{Manifest.Permission.ReadExternalStorage},1);
       
         }
      }
}

上面的代码可以很好地自我检查权限并请求权限,我遇到的唯一问题是检测用户是授予还是拒绝,然后调用 activity.FinishAffinity()

在 activity

中尝试 onRequestPermissionsResult
  @TargetApi(Build.VERSION_CODES.M)
  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
      case 101: {
        for (int i = 0; i < permissions.length; i++) {
          if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
          // when user denied permission
          } else {
           // when user allow permission
          }
        }
        break;
      }
    }
  }