In the production app we have seen few cases where getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath method call is causing the ANR issue.
So to solve this issue can we utilize the Coroutine?
something like this
lifecycleScope.launch {
val envPath = withContext(Dispatchers.IO) { getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath.orEmpty() }
// code, which will utilize the envPath
}
as the getExternalFilesDir() method is the part of ContextWrapper so will it create any problem if we will call it inside a different thread using the coroutine?
getExternalFilesDir uses android.os.storage.StorageManager which is Android system service. StorageManager is executed in a separate process, so it may block for a large of time.
Kotlin Coroutines: Deep Dive (Dispatchers chapter) recommends using Dispatchers.IO for code that may block a thread.
To sum up, it totally makes sense to use background thread for getExternalFilesDir.