Skip to content

Instantly share code, notes, and snippets.

@KatieBarnett
Created January 13, 2025 22:32
Show Gist options
  • Save KatieBarnett/9e76ed9ef1558677d75e33f911132c45 to your computer and use it in GitHub Desktop.
Save KatieBarnett/9e76ed9ef1558677d75e33f911132c45 to your computer and use it in GitHub Desktop.
Downloading an image to a file in a Coroutine Worker - Part 3
private suspend fun downloadImage(...): String {
...
// Get the path of the loaded image from DiskCache.
val path = context.imageLoader.diskCache?.openSnapshot(url)?.use { snapshot ->
...
// Find the current launcher every time to ensure it has read permissions
val intent = Intent(Intent.ACTION_MAIN).apply { addCategory(Intent.CATEGORY_HOME) }
val resolveInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.packageManager.resolveActivity(
intent,
PackageManager.ResolveInfoFlags.of(PackageManager.MATCH_DEFAULT_ONLY.toLong())
)
} else {
context.packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY)
}
val launcherName = resolveInfo?.activityInfo?.packageName
if (launcherName != null) {
// Request the permission
context.grantUriPermission(
launcherName,
contentUri,
FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_PERSISTABLE_URI_PERMISSION,
)
}
// return the path
contentUri.toString()
}
return requireNotNull(path) {
"Couldn't find cached file"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment