I'm storing mp3, mp4, jpg and an app own aw format on app's cache dir and using the next piece of code to clear that tmp files after they're used:
private fun deleteTmp() {
val rootFolder = File(context.cacheDir.absolutePath)
val mp4 = ".*\\.mp4"
val mp3 = ".*\\.mp3"
val jpg = ".*\\.jpg"
val gif = ".*\\.gif"
val aw = ".*\\.aw"
val folder = File("$rootFolder/")
val files = folder.listFiles { _, name ->
(name.matches(mp4.toRegex()) || name.matches(mp3.toRegex())
|| name.matches(jpg.toRegex()) || name.matches(gif.toRegex()) || name.matches(aw.toRegex()))
}
if (files != null) {
for (file in files) {
file.delete()
}
}
}
It was working perfectly until I upgraded "compileSdk" from 29 to 35 in build.gradle (to support newest devices), now listFiles it only gets folders, not files.
As far as I know you don't need permissions to list your app's own files, in fact these are files that I have created myself, so where's the problem?
I tried with filesDir also to no avail so I'm stuck.
I definitely wouldn't like to go over the tedious task of requesting permissions to the user in my activity, also consider nonsense to ask a user for permissions to delete tmp files I created myself, in fact, that app's internal process have to be transparent to the user.
Any help?
Edit 1: Skipping rootFolder and going directly to context.cacheDir.listFiles()
Exactly the same happens, only see folders.
BTW, in my case context.filesDir -> /data/user/0/com.xxx.xxx/cache
After thorough testing I can confirm that listFiles is not getting files from cacheDir (only folders), but it works on filesDir.
It has much more sense to store tmp files in cacheDir, because this is what they are, but given I cannot access them later, I'll swap to filesDir and work on there.
Still don't understand why listFiles is not working for cacheDir, but for the moment I found a solution to my issue.