Android-权限申请处理和框架EasyPermissions

2020-03-26  本文已影响0人  晴天ccc

前言

在Android6.0之后,谷歌对于应用程序权限进行的规范,对于特殊权限必须明确需要让用户授权。
这里有一个好用的权限相关的库EasyPermissions

传统方法权限申请处理

MainActivity


public class MainActivity extends AppCompatActivity {

    private ImageView leftImgView;

    // requestCode请求码用于结果回调里判断
    private static final int TAKE_PHOTO_REQUEST_CODE = 1;
    public static final int PERMISSIONS_REQUEST_CODE = 1;
    public static final int CAMERA_AND_LOCATION_CODE = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        ImageView takePicBtn = findViewById(R.id.takePicBtn);
        takePicBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestPermission();
            }
        });
    }

    // 权限申请
    private void requestPermission() {
        // 权限判断
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 无权限
            // 请求系统权限,传参需要申请的权限(可以多个)
            String[] perms = new String[]{Manifest.permission.CAMERA};
            ActivityCompat.requestPermissions(this, perms, RC_CAMERA_AND_LOCATION);
        } else {
            //有权限
            takePhoto();
        }
    }

    // 权限结果回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (RC_CAMERA_AND_LOCATION == requestCode) {
            for (int x : grantResults) {
                if (x == PackageManager.PERMISSION_DENIED) {
                    // 权限拒绝了
                    Toast.makeText(MainActivity.this, "权限拒绝了", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            // 权限通过了
            takePhoto();
        }
    }

    // 系统相机拍摄
    private void takePhoto() {
        //用来打开相机的Intent
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //判断是否具有相机权限
        if (takePhotoIntent.resolveActivity(getPackageManager()) != null) {
            //启动相机
            startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST_CODE);
        }
    }

    // 系统相机回调方法
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TAKE_PHOTO_REQUEST_CODE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap data1 = (Bitmap) extras.get("data");
            leftImgView.setImageBitmap(data1);
        }
    }
}

  • ContextCompat.checkSelfPermission()判断有具有相关权限。
  • ActivityCompat.requestPermissions()去请求权限。
  • onRequestPermissionsResult()在Activity中重写onRequestPermissionsResult() 来获取回调结果。在里面处理业务逻辑。

EasyPermissions的简单使用

依赖导入

     //EasyPermissions权限管理框架
    implementation 'pub.devrel:easypermissions:3.0.0'

Activity / Fragment实现PermissionCallbacks接口。

public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

}

MainActivity中修改和增加如下方法即可

    // 权限申请
    @AfterPermissionGranted(PERMISSIONS_REQUEST_CODE)
    private void requestPermission() {
        String[] perms = {Manifest.permission.CAMERA};
        //权限判断,第一次弹出系统的授权提示框
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 有权限
            // 直接执行
            takePhoto();
        } else {
            // 没有权限
            // 仅在权限授权时会执行该方法
            EasyPermissions.requestPermissions(
                    new PermissionRequest.Builder(this, CAMERA_AND_LOCATION_CODE, perms)
                            .setRationale("拍照过程需要用到相机权限")
                            .setPositiveButtonText("去授权")
                            .setNegativeButtonText("取消")
                            .build());
        }
    }
    
    // 权限结果回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 将权限处理结果传递给EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        // 授予权限
        // ...
        Toast.makeText(ContrastCreateActivity.this, "权限授予了", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        // 请求权限被拒
        // ...
        Toast.makeText(ContrastCreateActivity.this, "权限拒绝了", Toast.LENGTH_SHORT).show();
        // 弹框提示用户跳转设置打开权限
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

  • EasyPermissions.hasPermissions(Context context,String... perms)用于检查权限是否授权,第二个参数可传多个权限值。
  • EasyPermissions.requestPermissions(context,String rationale,int requestCode,String... perms)用于请求权限,rationale 是提示文字,requestCode请求码,perms是多个权限值。
上一篇下一篇

猜你喜欢

热点阅读