2020-12-11 kotlin fragment 动态申请权限

在Fragment中申请运行时权限的时候是使用Fragment本身来进行申请
在Activity中使用的时候我们的代码如下:

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
        1);

我们在Fragment中申请时不是使用AcyivityCompat而是使用Fragment本身,代码如下:
下面是kotlin 的写法,如果是java的话

HomeFragment.this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
        1);
    private val PERMISSION_CAMERA_REQUEST_CODE = 101


fun checkPermissionAndCamera() {
        val checkSelfPermission =
            ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.CAMERA)
        if (checkSelfPermission == PackageManager.PERMISSION_GRANTED){
            navitionToScan()
        }else{
            val list=arrayOf(Manifest.permission.CAMERA)
            requestPermissions( list, PERMISSION_CAMERA_REQUEST_CODE)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array,
        grantResults: IntArray
    ) {
        if (requestCode == PERMISSION_CAMERA_REQUEST_CODE){
            if (grantResults.isNotEmpty() &&
                grantResults[0] == PackageManager.PERMISSION_GRANTED){
                navitionToScan()
            }else{
                longToast(getString(R.string.camera_permission_deny))
            }
        }
    }

你可能感兴趣的:(2020-12-11 kotlin fragment 动态申请权限)