Android 10: What are my options to save files on external storage into a directory called “/sdcard/my-app/”

后端 未结 1 1967
逝去的感伤
逝去的感伤 2020-12-24 12:25

Up until Android Pie I always stored files which the app needed to get stored on /sdcard/my-app/, which I got via

File fBaseDir = new File(Environ

1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-24 12:36

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

    1. Use the manifest option requestLegacyExternalStorage 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 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.

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

    0 讨论(0)
提交回复
热议问题