问题
I'm trying to set wallpaper on a periodic basis and for that, I'm using the Work manager. When I make a network request from a background thread (CoroutineWorker), my app UI freezes till network request & set wallpaper completes.
I've already tried to run this using Async Task as well, but no use.
@WorkerThread
override suspend fun doWork(): Result = coroutineScope {
try {
MainService.createRetrofitService().getRandomPhoto(map)
.enqueue(object : Callback<RandomPhotoModel> {
override fun onFailure(call: Call<RandomPhotoModel>, t: Throwable) {
Log.e(Constants.Tag, t.localizedMessage)
}
override fun onResponse(call: Call<RandomPhotoModel>, response: Response<RandomPhotoModel>) {
if (response.isSuccessful) {
Glide.with(appContext).asBitmap().load(checkAndReturnImage(response.body()!!))
.into(object : SimpleTarget<Bitmap>() {
override fun onResourceReady(
resource: Bitmap,
transition: Transition<in Bitmap>?
) {
val wallpaperManager = WallpaperManager.getInstance(applicationContext)
wallpaperManager.setBitmap(resource)
}
})
}
}
})}catch (throwable: Throwable) {
Log.e(Constants.Tag, "Error applying wallpaper", throwable)
Result.failure()
} catch (e: Exception) {
Log.e(Constants.Tag, "Error applying wallpaper")
Result.failure()
}
I'm expecting the app should not be frozen while making a network request or setting up wallpaper in the background.
来源:https://stackoverflow.com/questions/56220613/my-app-freezes-when-i-make-a-network-request-in-background-thread-using-corouti