androidfile-permissions

Change file permsission on Android app programmatically


In my Android app, I want to create files preserved in case of app uninstallation.

I can create hidden file in

File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), ".SecretFolder")

My goal is to change read and write permission for this file.

I tried to uninstall my app -> File is preserved. After installation at reaf time I get AccessDeniedException

Now if I want to change read and write permission using File.setReadable(true, false) and File.setWritable(true, false), I can observe no change in Android Device File explorer (remains -rw-------) even if the API return true for both.

Note: I'm using a Virtual Device based on Android 11, API 30. I'm not targetting this version specifically

here is my code:

private fun writeFileOnInternalStorage(remainingToken : Int) {
            val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), ".SecretFolder")
            if(!dir.exists()){
                if(dir.mkdirs()){
                    var allowed = dir.setReadable(true, false)
                    println("DBEUG dir ${dir.toPath()} is world-readable ? $allowed")
                    allowed = dir.setWritable(true, false)
                    println("DBEUG dir ${dir.toPath()} is world-writable ? $allowed")
                }else{
                    println("ERROR")
                    return
                }
            }
            val f = File(dir, ".secretFile")
            if(!f.exists()){
               f.createNewFile()
               var allowed = f.setReadable(true, false)
                println("DBEUG ${f.toPath()} is world-readable ? $allowed")
               allowed = f.setWritable(true, false)
                println("DBEUG ${f.toPath()} is world-writable ? $allowed")
            }
            f.writeText(remainingToken.toString())
            println("DEBUG: written Internal Storage \"${remainingToken}\" in " + f.toPath().toString())
        }

Solution

  • You do not have rights to that file, and so you do not have rights to change the permissions of that file. A file in Documents/ can only be accessed by the app that created the file, and only for the specific installation of that app. Apps that are uninstalled and reinstalled are considered to be independent installations.

    (I doubt that technique would work anyway, as Android manages file permissions differently)

    Ordinarily, I would steer you to the Storage Access Framework. However, that is designed to do what users want: give them control over the storage. You appear to be attempting to hide your activity from the user ("create hidden file"). Google, device manufacturers, and users are working very hard to prevent developers from doing this.