Android 6.0以上版本动态请求权限

Demo地址:https://github.com/mlsnatalie/AddPicture

1.使用依赖动态请求权限

1、在Manifest里设置权限

2、引入github上的依赖库 github项目地址:https://github.com/mlsnatalie/Asi-libraryimplementation 'com.github.dfqin:grantor:2.5'

3、在需要请求权限的地方,写入方法 requestReadPhoneState() 4、请求权限的具体方法

private fun requestReadPhoneState() {

        PermissionsUtil.requestPermission(this, object : PermissionListener {
            override fun permissionDenied(permission: Array) {
                Toast.makeText(this@MainActivity, "访问内部存储", Toast.LENGTH_LONG).show()
            }

            override fun permissionGranted(permission: Array) {
                Toast.makeText(this@MainActivity, "用户拒绝了访问内部存储", Toast.LENGTH_LONG).show()
            }

        }, Manifest.permission.READ_EXTERNAL_STORAGE)
    }

2.第二种动态申请权限的方法

1.在MainActivity继承的BaseActivity里,写入动态申请权限的方法

 /**
     * 权限授权回调
     */
    PermissionListener mPermissionListener;
    
    
    
    /**
     * 权限申请
     * @param permissions
     * @param listener
     */
    protected void requestRunTimePermission(String[] permissions, PermissionListener listener) {

        //todo 获取栈顶activity,如果null。return;

        this.mPermissionListener = listener;

        List permissionList = new ArrayList<>();
        for (String permission : permissions) {
            if(ContextCompat.checkSelfPermission(this,permission)!= PackageManager.PERMISSION_GRANTED){
                permissionList.add(permission);
            }
        }
        if(!permissionList.isEmpty()){
            ActivityCompat.requestPermissions(this,permissionList.toArray(new String[permissionList.size()]),1);
        }else{
            listener.onGranted();
        }
    }

    /**
     * 申请结果
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 1:
                if (grantResults.length>0){
                    List deniedPermissions = new ArrayList<>();
                    List grantedPermissions = new ArrayList<>();
                    for (int i = 0; i < grantResults.length; i++) {
                        int grantResult = grantResults[i];
                        if (grantResult != PackageManager.PERMISSION_GRANTED){
                            String permission = permissions[i];
                            deniedPermissions.add(permission);
                        }else{
                            String permission = permissions[i];
                            grantedPermissions.add(permission);
                        }
                    }

                    if (deniedPermissions.isEmpty()){
                        mPermissionListener.onGranted();
                    }else{
                        mPermissionListener.onDenied(deniedPermissions);
                        mPermissionListener.onGranted(grantedPermissions);
                    }
                }
                break;
        }
    }

2、写PermissionListener的回调接口

public  interface PermissionListener {
    //全部授权成功
    void onGranted();
    //授权部分
    void  onGranted(List grantedPermission);
    //拒绝授权
    void  onDenied(List deniedPermission);
}

3、MainActivity继承接口,写回调方法

class MainActivity : BaseActivity(), PreparePictureView, PermissionListener {
    override fun onGranted() {
        Toast.makeText(this@MainActivity, "访问内部存储", Toast.LENGTH_LONG).show()
    }

    override fun onGranted(grantedPermission: MutableList?) {
        Toast.makeText(this@MainActivity, "访问内部存储", Toast.LENGTH_LONG).show()
    }

    override fun onDenied(deniedPermission: MutableList?) {
    }
}

4、在需要申请权限的地方

val array = arrayOfNulls(1)
        array[0] = Manifest.permission.READ_EXTERNAL_STORAGE
        requestRunTimePermission(array, this)

3.第三种申请权限的方法

1.在manifest里面申请


    
    

2.申请权限的方法

/**
     * Requests given permission.
     * If the permission has been denied previously, a Dialog will prompt the user to grant the
     * permission, otherwise it is requested directly.
     */
    protected fun requestPermission(permission: String, rationale: String, requestCode: Int) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            showAlertDialog(getString(R.string.permission_title_rationale), rationale,
                DialogInterface.OnClickListener { dialog, which ->
                    ActivityCompat.requestPermissions(
                        this,
                        arrayOf(permission), requestCode
                    )
                }, getString(R.string.label_ok), null, getString(R.string.label_cancel)
            )
        } else {
            ActivityCompat.requestPermissions(this, arrayOf(permission), requestCode)
        }
    }

    /**
     * This method shows dialog with given title & message.
     * Also there is an option to pass onClickListener for positive & negative button.
     *
     * @param title                         - dialog title
     * @param message                       - dialog message
     * @param onPositiveButtonClickListener - listener for positive button
     * @param positiveText                  - positive button text
     * @param onNegativeButtonClickListener - listener for negative button
     * @param negativeText                  - negative button text
     */
    protected fun showAlertDialog(
        title: String?, message: String?,
        onPositiveButtonClickListener: DialogInterface.OnClickListener?,
        positiveText: String,
        onNegativeButtonClickListener: DialogInterface.OnClickListener?,
        negativeText: String
    ) {
        val builder = AlertDialog.Builder(this)
        builder.setTitle(title)
        builder.setMessage(message)
        builder.setPositiveButton(positiveText, onPositiveButtonClickListener)
        builder.setNegativeButton(negativeText, onNegativeButtonClickListener)
        mAlertDialog = builder.show()
    }

3.使用的地方

 private fun pickFromGallery() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermission(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                getString(R.string.permission_read_storage_rationale),
                REQUEST_STORAGE_READ_ACCESS_PERMISSION
            )
        } else {
            val intent = Intent(Intent.ACTION_GET_CONTENT)
                .setType("image/*")
                .addCategory(Intent.CATEGORY_OPENABLE)

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                val mimeTypes = arrayOf("image/jpeg", "image/png")
                intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
            }

            startActivityForResult(Intent.createChooser(intent, getString(R.string.label_select_picture)), 1)
        }
    }

 

4.第四种动态申请权限的方法(推荐使用)

1.写动态权限类


class PermissionHelper(private val mActivity: Activity, private val mPermissionInterface: PermissionInterface) {
    private var permission: String? = null
    private var callBackCode: Int = 0

    /**
     * 请求权限
     * @param permission 权限名字
     * @param callBackCode 回调code
     */
    fun requestPermissions(permission: String, callBackCode: Int) {
        this.permission = permission
        this.callBackCode = callBackCode
        if (hasPermission(mActivity, permission)) {
            mPermissionInterface.requestPermissionsSuccess(callBackCode)
        } else {
            ActivityCompat.requestPermissions(mActivity, arrayOf(permission), callBackCode)
        }

    }

    /**
     * 在Activity中的onRequestPermissionsResult中调用,用来接收结果判断
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    fun requestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
        if (requestCode == callBackCode) {
            for (result in grantResults) {
                if (result == PackageManager.PERMISSION_GRANTED) {
                    mPermissionInterface.requestPermissionsSuccess(callBackCode)
                } else {
                    mPermissionInterface.requestPermissionsFail(callBackCode)
                }
            }
        }
    }

    companion object {

        /**
         * 判断是否有某个权限
         *
         * @param context
         * @param permission
         * @return
         */
        fun hasPermission(context: Context, permission: String): Boolean {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // Android 6.0判断,6.0以下跳过。在清单文件注册即可,不用动态请求,这里直接视为有权限
                if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false
                }
            }
            return true
        }
    }
}

2. 动态申请权限的接口

interface PermissionInterface {
    /**
     * 请求权限成功回调
     */
    fun requestPermissionsSuccess(callBackCode: Int)

    /**
     * 请求权限失败回调
     */
    fun requestPermissionsFail(callBackCode: Int)

}

3. 申请权限方法在Activity中的具体使用

private const val REQUEST_CODE_ADD_PICTURE = 33

class FourthActivity : AppCompatActivity(), PermissionInterface {

    private var permissionHelper: PermissionHelper? = null
    // 拍照结果返回code
    private val REQ_CODE_PICK_PHOTO = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_fourth)

        permissionHelper = PermissionHelper(this, this)
        initView()

    }

    private fun initView() {
        // 拍照监听
        bt_photo.setOnClickListener { // lambda 简写
            // 判断是否有权限
            permissionHelper?.requestPermissions(Manifest.permission.CAMERA, 1)
        }
    }


    /**
     * 重写Activity的权限请求返回结果方法
     *
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
        permissionHelper?.requestPermissionsResult(requestCode, permissions, grantResults) // 接管结果判断
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    override fun requestPermissionsSuccess(callBackCode: Int) { // 有权限处理
        if (callBackCode == REQ_CODE_PICK_PHOTO) {
            takePhoto()
        }
    }

    override fun requestPermissionsFail(callBackCode: Int) { // 无权限处理
        if (callBackCode == REQ_CODE_PICK_PHOTO) {
            Toast.makeText(this, "sd", Toast.LENGTH_LONG).show()
        }
    }

    // 处理有权限后的业务逻辑
    private fun takePhoto() {
        val intent = Intent()
        intent.type = "image/*"
        intent.action = Intent.ACTION_GET_CONTENT
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_CODE_ADD_PICTURE)
    }


}

参考:https://blog.csdn.net/loveyouxuan/article/details/83409941

 

Demo地址: https://github.com/mlsnatalie/RequestPermissionDeom

你可能感兴趣的:(Android 6.0以上版本动态请求权限)