In my app, I am saving files of different types of images, videos, pdf, etc. I am creating a directory if it does not already exist and saving the files generated by my app in that folder so that the user can easily find the files used and created by my app. But in Android 10 I'm unable to check and create directory in external storage.
I know that I can add android:requestLegacyExternalStorage="true"
in my manifest to continue to use the old functionality but this is not the permanent solution. Also, I don't want to use getExternalFilesDir()
as this folder created by this method will be deleted if the user uninstalls my app, and I want the files saved by the app to remain in his device so that those files can be used again.
This is the code I am using at present to check and create a directory of my app and store a file "myFile" in that directory.
File sd =Environment.getExternalStorageDirectory();
File directory = new File(sd.getAbsolutePath() + "/" + getResources().getString(R.string.app_name));
//create directory if not exist
if (!directory.isDirectory()) {
directory.mkdirs();
}
File file = new File(directory, myFile);
How can I achieve the same result in Android 10? What I exactly want is:
- To check whether a directory with my app name exists or not. If the directory does not exist then create the directory in device external storage.
- Save all the files generated by my app in this directory.
- This folder should not get deleted even if the user uninstalls the app.
- Read files from this folder.