android 11后对文件读写访问权限管理 与 android 10又有了新的要求,导致在读写或者访问时出现error:java.io.FileNotFoundException: /storage/emulated/0/file_path open failed: EACCES (Permission denied),以下为android 11文件管理权限申请办法
import android.provider.Settings if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R){ val uri = Uri.parse("package:${BuildConfig.APPLICATION_ID}") startActivity( Intent( Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, uri ) ) }
回忆android 10 文件访问权限申请
step 1: AndroidManifest中添加权限申请配置
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/> <application android:requestLegacyExternalStorage="true"> <provider android:name="androidx.core.content.FileProvider" android:authorities="com.xxx.xxx.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths_app" /> </provider> </application>
step 2: res/xml 资源文件夹下创建file_paths_app.xml 名称可以随意,与provider中配置resource同步
<?xml version="1.0" encoding="utf-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android"> <paths> <external-path name="external-path" path="." /> <external-files-path name="external-files-path" path="." /> <external-cache-path name="external-cache-path" path="." /> <files-path name="files-path" path="." /> <cache-path name="cache-path" path="." /> </paths> </resources>
Tag 对应的路径 root-path 根目录/ files-path /data/user/0/<package_name>/files 或者/data/data/<package_name>/files 这两个目录指向相同的位置 cache-path /data/user/0/<package_name>/cache 或者 /data/data/<package_name>/cache external-path /storage/emulated/0或者/sdcard/ external-files-path /storage/emulated/0/Android/data/<package_name>/files 或者 /sdcard/Android/data/<package_name>/files external-cache-path /storage/emulated/0/Android/data/<package_name>/cache 或者 /sdcard/Android/data/<package_name>/cache
step 3:调用文件读写权限申请
AppPermissionReq.INSTANCE.permissionReq( this, defPermissions, object : PassPermission { override fun unauthorized() { } override fun authorized() { } })