【问题标题】:Migrating from AsyncTask to Coroutines in Android?在 Android 中从 AsyncTask 迁移到协程?
【发布时间】:2020-01-16 10:07:20
【问题描述】:

我是协程新手。这是一个普遍的问题。我已经研究过其他问题,但它们更针对特定用例。

目前,我正在使用以下基于回调的架构:

class MyService: Service(), OnComplete {
...
companion object {
   lateinit var serviceContext: Context
}
...
override fun onCreate() {
   super.onCreate()
   serviceContext = this
}
...
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
   MyAsyncTask().execute()     // start the background job
   return super.onStartCommand(intent, flags, startId)
}
...
override fun onCompleteFunc(resultBundle: Bundle) {
   // do something when the job is finished
}
}

AsyncTask如下:

class MyAsyncTask: AsyncTask<Any, Any, Any>() {
...
val onComplete by lazy { MyService.serviceContext as OnComplete }
...
override fun doInBackground(vararg params: Any?): Any {
   // do the background job here
   // store the results somewhere
   return 0
}
...
override fun onPostExecute(result: Any?) {
   super.onPostExecute(result)
   onComplete.onCompleteFunc( // job finished. send the results
      Bundle().apply { 
         // put extras here
      }
   )
}
}

还有界面:

interface OnComplete {
   fun onCompleteFunc(resultBundle: Bundle)
}

我对迁移到 kotlin 协程非常感兴趣。请帮我解决这个问题。

问候, 赛扬坦

【问题讨论】:

  • 请不要因为他们的英语不完美而对别人发火,尤其是当他们努力保持礼貌时。阻碍他们的是他们不知道如何进行。呃。在这种情况下,有用的链接可能会很有帮助。 (codelabs 可以帮助您理解协程,但无助于将 AsyncTask 转换为协程;这不是他们教程的一部分。)

标签: android android-asynctask kotlin-coroutines


【解决方案1】:

我建议你使用work manager代替service,你可以使用Coroutine Worker 并在那里添加你所有的工作,你可以使用 setForground(notification) 方法来显示来自工作人员的通知,请参阅 medium 中的博客。我希望我已经回答了你的问题

https://medium.com/androiddevelopers/workmanager-meets-kotlin-b9ad02f7405e

【讨论】:

    猜你喜欢
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多