解决Android13上读取本地文件权限错误记录

Android13  WRITE_EXTERNAL_STORAGE 权限失效

1. 需求及问题

  1. 需求是读取sdcard上txt文件

  2. Android13(targetSDK = 33)上取消了WRITE_EXTERNAL_STORAGEREAD_EXTERNAL_STORAGE权限。

  3. 取而代之的是READ_MEDIA_VIDEOREAD_MEDIA_AUDIOREAD_MEDIA_IMAGES权限

  4. 测试发现,即便动态申请上面三个权限,仍旧无法读取本地txt文件

2c6403c4114ac2e21a9f61d577c36cac.png

2. 解决方案

  1. AndroidManifest.xml中增加android.permission.MANAGE_EXTERNAL_STORAGE权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.LocationDemo"
        tools:targetApi="31">


        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>


</manifest>
  1. Activity中新增代码

// 方案一:跳转到系统文件访问页面,手动赋予
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.setData(Uri.parse("package:" + this.getPackageName()));
startActivity(intent);

cb8db8f02a2187bd28bb0939b17e8340.png

// 方案二:跳转到系统所有需要文件访问页面,选择你的APP,手动赋予权限
Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivity(intent);

84d9bfd6b2ade68bc1559279b4af0552.png

作者:OpenGL
链接:https://juejin.cn/post/7283152332622610492

关注我获取更多知识或者投稿

990069380a14beed01e8eacfb00333f6.jpeg

ef450fdd2273b262bbb657eb43c55c46.jpeg