![](/img/trans.png)
[英]Transition from AsyncTask to Coroutines in Retrofit: IllegalArgumentException
[英]Migrating from AsyncTask to Coroutines in Android?
我是協程的新手。 這是一個普遍的問題。 我研究了其他問題,但它們更具體地針對特定用例。
目前,我正在使用以下基於回調的架構:
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 協程非常感興趣。 請幫我解決這個問題。
問候, 薩彥坦
我建議您使用工作管理器而不是服務,您可以使用Coroutine Worker並將您的所有工作添加到那里,您可以使用setForground(notification)方法來顯示來自工作器的通知,請參閱媒體中的博客。 我希望我已經回答了你的問題
https://medium.com/androiddevelopers/workmanager-meets-kotlin-b9ad02f7405e
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.