androidscoped-storage

Android 11 - Creating app-specific directory on external storage


Recently, I'm trying to migrate my application from SDK-29 to SDK-30. And one thing I concerned the most is scoped storage.

I saw on official document that says "On Android 11 (API level 30) and higher, apps cannot create their own app-specific directory on external storage."

So I tried it out to create my own directory inside external storage and write a new file to it. The code looks like this :

// creating new directory under external storage
val appDir = File(applicationContext.getExternalFilesDir(null), "play")
appDir.mkdir()

// writing new file under my own directory
val newFile = File(appDir.absolutePath, "test.jpg")
val outputStream = FileOutputStream(newFile)
val inputStream = resources.openRawResource(R.drawable.ic_launcher_foreground)
val data = byteArrayOf()
inputStream.read(data)
outputStream.write(data)
inputStream.close()
outputStream.close()

I expected this code will crash but it works. I find the file at the given path. So, I'm a little confused the meaning of that note.

What do Google means with "cannot create their own app-specific directory on external storage"?


Solution

  • They are referring to creating arbitrary directories off of the external storage root (e.g., Environment.getExternalStorageDirectory().

    getExternalFilesDir() and similar methods on Context are fine solutions to use instead!