Android 11 accesses files or saves extracted pictures to a directory

foreword

I encountered a problem today. It is effective to save pictures to the directory under Android 10, but not on Android 11.

The code in question is this

String path = Environment.getExternalStorageDirectory()+"/DirName/"+"123.jpg";

The above code gets the root directory of the file.

The final solution is to replace the above code with the following code:

//下面这段代码获取的目录是//storage/emulated/0/Android/data/com.microhabit/files/DirName/123.jpg
String path = MyApplication.context.getExternalFilesDir(null)+ "/DirName/"+"123.jpg"

Reason: In the Android 11 version, third-party applications are not allowed to create directories and files at will in the user folder. (Actually, this is also a good thing for users), so use it on higher versions

Environment.getExternalStorageDirectory()

This sentence to get the external directory and create a folder is invalid.

It should be noted that if you put the file in the directory obtained by MyApplication.context.getExternalFilesDir(null),

When the application is uninstalled, the files in this directory will be deleted together.

Other notes: To solve the above problem, I did not use FileProvider and add these two sentences in the manifest file

  <!--注意:解决上面的问题 没加入这两句话也好使-->
 android:requestLegacyExternalStorage="true"
  android:preserveLegacyExternalStorage="true"

Complete code snippet:

    /**
     * 获取头像保存位置
     * @return
     */
    public static String getHeadPath(String user_id) {
        String mFile = null;
        if (mFile == null) {
            //mFile = Environment.getExternalStorageDirectory()+ "/MicroHabit/"+user_id+".jpg";
            //String path = Environment.getExternalStorageDirectory() + "/MicroHabit";
             if(MyApplication.context==null){
                return "";
             }
            String path =  MyApplication.context.getExternalFilesDir(null) + "/MicroHabit";
            mFile = MyApplication.context.getExternalFilesDir(null)+ "/MicroHabit/"+user_id+".jpg";
            //storage/emulated/0/Android/data/com.microhabit/files/MicroHabit/111.jpg
            File filePath = new File(path);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
        }
        return mFile;
    }

Summarize:

In versions above Android 11, files cannot be created outside of its own application directory.

It seems that the permission can be obtained through fileprovide, but it has not been tried on version 11 yet.

Supongo que te gusta

Origin blog.csdn.net/gaoqingliang521/article/details/123072175
Recomendado
Clasificación