Android中代码申请权限(应对android6.0以上)

if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PERMISSION_GRANTED) {//判断是否已经赋予权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                //这里可以写个对话框之类的项向用户解释为什么要申请权限,并在对话框的确认键后续再次申请权限.它在用户选择"不再询问"的情况下返回false

            } else {
                //申请权限,字符串数组内是一个或多个要申请的权限,1是申请权限结果的返回参数,在onRequestPermissionsResult可以得知申请结果
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}}

重写onRequestPermissionsResult
{
if (requestCode == 1) {//requestCode的值是上边的1 
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PERMISSION_GRANTED) {
                    Toast.makeText(this, "" + "权限" + permissions[i] + "申请成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "" + "权限" + permissions[i] + "申请失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
}

  

宿主Activity中
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
  {
       super.onRequestPermissionsResult(requestCode, permissions, grantResults);
       // 获取到Activity下的Fragment
       List<Fragment> fragments = getSupportFragmentManager().getFragments();
       if (fragments == null)
       {
           return;
       }
       // 查找在Fragment中onRequestPermissionsResult方法并调用
       for (Fragment fragment : fragments)
       {
           if (fragment != null)
           {
               // 这里就会调用我们Fragment中的onRequestPermissionsResult方法
               fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
           }
       }
   }

2.Fragment 中 只用如下方式请求权限

fragment.requestPermissions(mPermissionList,REQUEST_CODE_CAMERA)
而不是 ActivityCompat/ContextCompat

ActivityCompat.requestPermissions((AppCompatActivity)context, new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE)

 

上一篇:Fragment扫描二维码 未触发onActivityResult


下一篇:Android | 教你如何开发扫二维码功能