The lack of permissions in Android 11 prevents the original file from being modified, and how to obtain access to all files

In the development of Android 11, the app will encounter a situation where a certain file cannot be opened using an absolute path (the file exists in the root directory, and the obtained path is: /storage/emulated/0/XXX.txt), and the relative path is used to open the file (the obtained path is: /data/user/0/com.XXX/files/XXX.txt), the original file cannot be modified, because the file opened with a relative path will be opened in a sandbox environment, even if the content is modified It only modifies the content of the file in the sandbox environment, and the original file has no effect.
If you want to read and write files on the entire device, you need to use Intent to jump to a special authorization page and guide the user to authorize manually. After obtaining the access permission, you can use the absolute path to read and write the original file. The operation is as follows:
First, declare the MANAGE_EXTERNAL_STORAGE permission in AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.demo">

    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
        tools:ignore="ScopedStorage" />

</manifest>

Also need to add under application

<application>
	android:requestLegacyExternalStorage="true"
	......
	......
</application>

Then, use the action ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION to jump to the specified authorization page.

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R ||
                Environment.isExternalStorageManager()) {
    
    
            Toast.makeText(this, "已获得访问所有文件的权限", Toast.LENGTH_SHORT).show();
        } else {
    
    
            Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
            startActivity(intent);
        }

If the permission to access all files is obtained, it will prompt; if not obtained, a pop-up window will let the user open it manually. With this permission, you can use absolute paths to read and write files.
However, many resources in the Android directory are still inaccessible. For example, the Android/data directory cannot be accessed by any means in Android 11. After all, it is not safe to access each other's data across apps.

Guess you like

Origin blog.csdn.net/qq_35761934/article/details/116588286