1)Target set to Android Q
with android.permission.WRITE_EXTERNAL_STORAGE
2) use getExternalStorageDirectory
or getExternalStoragePublicDirectory
and FileOutputStream(file)
saving file throws
java.io.FileNotFoundException: /storage/emulated/0/myfolder/mytext.txt open failed: ENOENT (No such file or directory)
3) use getExternalFilesDir
api 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.
In Android Q direct File access is disabled by default for the apps outside their private folders. Here few strategies you can use:
requestLegacyStorage
to have the old behavior but it won't work anymore with Android R, so it's really a short term solution;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.MediaStore
API to insert your media directly. This approach is good for videos, music and photos.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.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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With