外部存储访问权限(~Android 11)
Android 12之后体系就不允许自由访问外部存储了,只能访问指定的外部存储存储,例如:context.getExternalFilesDir(Environment.type)下的外部存储,大概其他/Android/data/data下的外部存储。
<!-- Without this folders will be inaccessible in Android-11 and above devices -->
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<!-- Without this entry storage-permission entry will not be visible under app-info permissions list Android-10 and below -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29" tools:ignore="ScopedStorage" />
<!-- Without this entry the folders will remain in-accessible in Android-10, even if WRITE_EXTERNAL_STORAGE as above is present. --><application android:requestLegacyExternalStorage="true" />
文件访问权限申请
老例子了,访问外部存储前必要申请权限。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val intent = Intent()
intent.action = Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION
val uri: Uri = Uri.fromParts("package", this.packageName, null)
intent.data = uri
startActivity(intent)
} else {
val intent = Intent(Settings.ACTION_APPLICATION_SETTINGS)
resultLauncher.launch(intent)
}
Android R以下申请权限
var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
PermissionUtil.requestPermissionStorage(this, Const.REQUEST_PERMISSION_STORAGE)
}
val PERMISSIONS_STORAGE = arrayOf(READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE)
fun requestPermissionStorage(activity: Activity, requestCode: Int): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
if (!checkPermissionsAuth(activity, PERMISSIONS_STORAGE)) {
val deniedPermissions = getDeniedPermissions(activity, PERMISSIONS_STORAGE).toTypedArray()
ActivityCompat.requestPermissions(activity, deniedPermissions, requestCode)
return false
}
}
return true
}
Android12后文件访问
此时不必要申请权限了,可以直接访问。如果你要分享就必要添加FileProvider设置。
val appDocDir = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
appContext.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)!!
} else {
Environment.getExternalStorageDirectory()
}
参考
WRITE_EXTERNAL_STORAGE when targeting Android 10 |