Home > Mobile >  Android 11 Storage Access and Java File Library
Android 11 Storage Access and Java File Library

Time:09-17

I have an android application already available on playstore. It is a file transfer app between PC to Android using localhost. I'm using following java function within it:

To create directory/file/show list of files and many other file functions(append, byte read/write etc):

file.mkdir
directory.listFiles();
file.createNewFile()

I had also put

 requestLegacyExternalStorage="true"

And it is working fine on android 10 after giving sufficient read/write external storage permission.

But the problem is that these will not work on android 11 as requestLegacyExternalStorage will not work. I have used MANAGE_EXTERNAL_STORAGE and the app works perfect but the problem is that playstore is not allowing it. (Don't know why they rejected the update)

I have also used getExternalFilesDir and it works perfect but don't like data to be in android folder and remove if app is deleted.

I have also tried to use download location and it works but the problem is getExternalStorageDirectory is deprecated:

File file = new File(Environment.getExternalStorageDirectory() "/" Environment.DIRECTORY_DOWNLOADS,"FileChat");

So what I wanted to ask how can I manage/use file library for android 11 to read/write/create/delete files and directory. It should not be in android folder as this will be deleted after app is deleted. Can I used public directory like downloads? If I can, what is the alternative to getExternalStorageDirectory()?

I don't need to read user data. Just want to have a directory in which app can store files. The read function is working as file is picked by user using intent.

Thanks in advance.

CodePudding user response:

Top-level directory write access of shared storage is not available in Android 11, however you can use the existing File APIs to access the media and download collection folders like /Pictures, /Downloads, /DICM etc. It won't be possible to create your app's own folder as top level directory but it is possible to create a dedicated sub-directory in the default collection folders.

To keep your app running as expected on Android 10, requestLegacyExternalStorage flag will also be required since access to shared storage on Android 10 was restricted via MediaStore APIs only.

CodePudding user response:

If transfer is only for your apps own files then put them in

File file = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_DOCUMENTS),"FileChat");

Or use Storage Access Framework to let the user choose and or create a directory on external storage inclusive removable micro sd card.

  • Related