androidfile-permissionsscoped-storage

Permission error when trying to read/write a file that is created by other app in Scoped Storage


I don't want to access the external storage, my app doesn't ask for any permissions, it only accesses the Scoped Storage. As I understand, Read/Write operations to Scoped Storage can work without any permissions.

I'm trying to read/write to a file in the "Downloads" folder. It works when it's created by the app itself. But if I manually put a file there using adb push, it shows error for both read and write operations:

exception: java.io.FileNotFoundException: /storage/emulated/0/Download/aaa.txt: open failed: EACCES (Permission denied)

The error even occurs after I re-install the app, making it impossible to restore the settings from a previous backup file.

Why and how to solve this? This is my code:

    // the file path: /storage/emulated/0/Download/aaa.txt
    val dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath
    val filename = "aaa.txt"

    val bytes = ByteArray(10)

    try {
        val file = File(dir, filename)

        file.readBytes() // read
        file.writeBytes(bytes) // write

        Log.e(TAG, "ok")
    } catch (e: Exception) {
        Log.e(TAG, "exception: $e")
    }

Solution

  • You're contradicting yourself, when using File I/O; instead use ContentResolver. Permissions depend if the FileProvider exposes these files with Intent.FLAG_GRANT_READ_URI_PERMISSION and/or Intent.FLAG_GRANT_WRITE_URI_PERMISSION. It may as well be that the app doesn't feature any FileProvider. For examples, see the Storage Samples Repository.

    Manage all files on a storage device also works, but is barely accepted by Google Play.
    In my opinion, it's a pity one cannot scope this permission down to one single directory;
    One can only hardcode Environment.DIRECTORY_DOWNLOADS, but not really ask for it.


    Hint: "restore the settings from a previous backup file" works whole differently on Android: