Android权限申请:自带方法 + 第三方库实现

Android自带权限申请方法:

 

1、权限申请:(第二个参数0是requestCode):

String [] permission = {Manifest.permission.ACCESS_FINE_LOCATION};
if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)  != PackageManager.PERMISSION_GRANTED){
    requestPermissions(permission,0);
}

 2、回调(你可以根据requestCode和permissions来做判断):

    @Override
    public void onRequestPermissionsResult(int requestCode,
         @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults[0] == PackageManager.PERMISSION_DENIED){
            finish();
        }
    }

第三方库1:RxPermissions:

1、依赖:

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

dependencies {
    implementation 'com.github.tbruyelle:rxpermissions:0.10.2'
}

2、使用: 

// Must be done during an initialization phase like onCreate
rxPermissions
    .request(Manifest.permission.CAMERA)//可填多个权限,逗号隔开
    .subscribe(granted -> {
        if (granted) { // Always true pre-M
           // I can control the camera now
        } else {
           // Oups permission denied
        }
    });

附上该库GitHub地址: https://github.com/tbruyelle/RxPermissions


第三方库2:grantor:

1、依赖:

implementation 'com.github.dfqin:grantor:2.5'

2、使用:

/**
 * 申请录音权限
 */
private void requestAudioPermission() {
    PermissionsUtil.requestPermission(getApplication(), new PermissionListener() {
        @Override
        public void permissionGranted(@NonNull String[] permissions) {
        }

        @Override
        public void permissionDenied(@NonNull String[] permissions) {
            showTip("请开启录音权限");
            XunfeiVoiceActivity.this.finish();
        }
    }, Manifest.permission.RECORD_AUDIO);
}


/**
 * 申请存储权限
 */
private void requestStoragePermission() {
    PermissionsUtil.requestPermission(getApplication(), new PermissionListener() {
        @Override
        public void permissionGranted(@NonNull String[] permissions) {
        }

        @Override
        public void permissionDenied(@NonNull String[] permissions) {
            Toast.makeText(MainActivity.this, "没有存储权限将不能预览本地视频", Toast.LENGTH_SHORT).show();
        }
    }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
}

附上该库GitHub地址:https://github.com/dfqin/PermissionGrantor

 

完。

你可能感兴趣的:(Android)