Android权限动态获取

效果.gif

首先在AndroidManifest中添加需要的权限,以相机和文件读写权限为例

    
    
    

通常在APP打开的第一个Activity中动态获取权限

//将所要请求的权限放在一个list集合中一起请求
 private var permissions = arrayOf(
   Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA)
 //存放未授权的权限
 private var UnauthorizedList: ArrayList = ArrayList()

 private val mRequestCode = 100

 private fun Permission() {
        if (Build.VERSION.SDK_INT >= 23){
            for (i in permissions.indices){
                if (ContextCompat.checkSelfPermission(this,permissions[i]) != PackageManager.PERMISSION_GRANTED){
                    //没有授权的权限
                    UnauthorizedList.add(permissions[i])
                }
            }
          //权限请求
         ActivityCompat.requestPermissions(this, UnauthorizedList, mRequestCode)
        }
  }

Android10以上文件读写权限需要在AndroidManifest的application中添加

  android:requestLegacyExternalStorage="true"

你可能感兴趣的:(Android权限动态获取)