How to get '/storage/emulated/0/Android/media/$packageName' folder path programmatically?


Currently I can use both

val path: File? = Environment.getExternalStorageDirectory()?.let { File(it, "Android/media/${context.packageName}") }

and

val path: File? = context.externalMediaDirs.firstOrNull()

Is there any better way to get the path considering externalMediaDirs is deprecated? Note that I want the path to store non media files there.

I was intending to use externalMediaDirs to get /storage/emulated/0/Android/Media/<package name> without hardcoding but according to this article by CommonsWare, if the returned array contains 2+ items, the first one usually will be the removable storage (let's assume microSD card) which is not what I want.

0
Mar 20 at 5:03 PM
User Avatarfaizul726
#android#kotlin

Accepted Answer

> if the returned array contains 2+ items, the first one usually will be the removable storage (let's assume microSD card)

No offense, but that is the exact opposite of what I wrote there:

> If the array has 2+ elements, all but the first will point to an app-specific directory on some removable medium. You can read and write files here, create subdirectories, etc.

(emphasis added)

The first element of the array will point to on-board storage on most devices. The second, third, etc. elements of the array, if they exist, will point to removable storage on most devices. The "on most devices" caveat is because there are weird devices out there with custom Android builds that might behave differently, based upon decisions made by their manufacturers.

> Is there any better way to get the path considering externalMediaDirs is deprecated?

No.

> Note that I want the path to store non media files there.

That is not a great idea IMHO. Use getExternalFilesDir() to get a directory where you can write whatever you want to, included non-media files. As a bonus, that function is not deprecated and will point to a location in on-board flash storage on most devices.

User AvatarCommonsWare
Mar 20 at 5:13 PM
0