Android外部存储兼容(Android12)

源代码 2024-10-1 14:49:24 31 0 来自 中国
外部存储访问权限(~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
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-11-21 23:21, Processed in 0.119307 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表