Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File operations in android Q beta

1)Target set to Android Q with android.permission.WRITE_EXTERNAL_STORAGE

2) use getExternalStorageDirectoryor getExternalStoragePublicDirectoryand FileOutputStream(file)saving file throws

java.io.FileNotFoundException: /storage/emulated/0/myfolder/mytext.txt open failed: ENOENT (No such file or directory)

3) use getExternalFilesDirapi and saving is success but wont show up even after MediaScannerConnection.scanFile.

     /storage/emulated/0/Android/data/my.com.ui/files/Download/myfolder/mytext.txt

What is best way to copy file from internal memory to SDCARD in android Q and refresh.

like image 291
NitZRobotKoder Avatar asked Aug 06 '19 07:08

NitZRobotKoder


2 Answers

In Android Q direct File access is disabled by default for the apps outside their private folders. Here few strategies you can use:

  1. Use the manifest option requestLegacyStorage to have the old behavior but it won't work anymore with Android R, so it's really a short term solution;
  2. Save your files using getExternalFilesDir() method. It's your private folder, other apps could access these files only if they have READ_EXTERNAL_STORAGE permission. In this case it would be good to use FileProvider to grant access to other apps to your files.
  3. Use MediaStore API to insert your media directly. This approach is good for videos, music and photos.
  4. Use the method getPrimaryStorageVolume().createOpenDocumentTreeIntent() of class StorageManager to ask for access to the extenal primary volume. In this case you need user consent and you won't be able to use File api directly anyway, but using DocumentFile class you have a very similar interface, so this is the solution closer to the old behavior. It works if you need to perform operations in foreground and background, i.e. without user interaction with the exception the first interaction to request the permission.
  5. Use ACTION_CREATE_DOCUMENT to create a file using SAF. This option is valid if you do this operation in foreground because you will need the folder selection by the user.

I link Flipper library for point 4, it helps to manage files like in older android versions.

like image 69
greywolf82 Avatar answered Oct 21 '22 20:10

greywolf82


If you use preserveLegacyExternalStorage, the legacy storage model remains in effect only until the user uninstalls your app. If the user installs or reinstalls your app on a device that runs Android 11, then your app cannot opt out the scoped storage model, regardless of the value of preserveLegacyExternalStorage.

Something to remember when using this flag. know more

like image 40
Pallav Srivastava Avatar answered Oct 21 '22 19:10

Pallav Srivastava