My app freezes when I make a network request in background thread (using CoroutineWorker & Work manager)

邮差的信 提交于 2020-01-14 05:32:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!