Skip to content

Instantly share code, notes, and snippets.

@KatieBarnett
Created January 13, 2025 05:54
Show Gist options
  • Save KatieBarnett/e0f100c3827aad0efe37812d8cfe52ec to your computer and use it in GitHub Desktop.
Save KatieBarnett/e0f100c3827aad0efe37812d8cfe52ec to your computer and use it in GitHub Desktop.
Downloading an image to a file in a Coroutine Worker
@OptIn(ExperimentalCoilApi::class)
private suspend fun downloadImage(
url: String,
context: Context,
applicationContext: Context,
force: Boolean
): String {
val request = ImageRequest.Builder(context)
.data(url)
.build()
// Request the image to be loaded and throw error if it failed
with(context.imageLoader) {
if (force) {
diskCache?.remove(url)
memoryCache?.remove(MemoryCache.Key(url))
}
val result = execute(request)
if (result is ErrorResult) {
throw result.throwable
}
}
// Get the path of the loaded image from DiskCache.
val path = context.imageLoader.diskCache?.openSnapshot(url)?.use { snapshot ->
val imageFile = snapshot.data.toFile()
// Use the FileProvider to create a content URI
val contentUri = getUriForFile(
context,
"${applicationContext.packageName}.provider",
imageFile,
)
// Find the current launcher everytime 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 {
@Suppress("DEPRECATION")
context.packageManager.resolveActivity(
intent,
PackageManager.MATCH_DEFAULT_ONLY,
)
}
val launcherName = resolveInfo?.activityInfo?.packageName
if (launcherName != null) {
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