Skip to content

Instantly share code, notes, and snippets.

@Astroa7m
Created June 30, 2022 14:11
Show Gist options
  • Save Astroa7m/446d92595d50c275a82bb1c2816d5f0a to your computer and use it in GitHub Desktop.
Save Astroa7m/446d92595d50c275a82bb1c2816d5f0a to your computer and use it in GitHub Desktop.
@Suppress("BlockingMethodInNonBlockingContext")
class RemoteImageWorker(
private val context: Context,
workerParameters: WorkerParameters
) : CoroutineWorker(
context,
workerParameters
) {
override suspend fun doWork(): Result {
return try {
// getting image category index
val currentCategoryIndex = inputData.getInt(CURRENT_CATEGORY, categories.lastIndex)
// getting the category string by the index
val query =
if (currentCategoryIndex == categories.lastIndex) "" else categories[currentCategoryIndex].name
// getting a single image object
val response = RemoteImageService.serviceInstance.getRandomImageObject(query = query)
response.body()?.let { remoteImage ->
// getting image raw bytes from image object url
RemoteImageService.serviceInstance.getRandomImageBytes(remoteImage.urls.regular)
.body()?.let {
//creating image file and writing bytes to that file
val imageFile = File(context.filesDir, "${UUID.randomUUID()}.jpg")
FileOutputStream(imageFile).use { stream ->
stream.write(it.bytes())
}
// deleting the previous image
context.filesDir.listFiles()?.let {
for (file in it) {
if (file.path.endsWith(".jpg") && file.path != imageFile.path)
file.delete()
}
}
//updating the widget
updateRemoteImageWidget(imageFile.path)
Result.success()
}
?: Result.failure(workDataOf(ERROR_MESSAGE to "Error occurred while retrieving image"))
}
?: Result.failure(workDataOf(ERROR_MESSAGE to "Error occurred while retrieving image object"))
} catch (e: Exception) {
e.printStackTrace()
Result.failure(workDataOf(ERROR_MESSAGE to e.localizedMessage))
}
}
private suspend fun updateRemoteImageWidget(imageUri: String) {
GlanceAppWidgetManager(context).getGlanceIds(RemoteWidget::class.java).forEach { glanceId ->
updateAppWidgetState(context, glanceId) { pref ->
pref[stringPreferencesKey(FILE_URI)] = imageUri
}
RemoteWidget().updateAll(context)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment