Service+协程
- 导入
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0'//lifecycleScope
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'//viewModelScope
-
启动协程
job = GlobalScope.launch -
停止协程
job?.cancel() -
Android 8.0 以上不推荐使用IntentService了,Google推荐使用JobIntentService
- 由于线程的不好控制,可以使用协程来代替
- 协程中的任务完成后,停止Service
override fun onCreate() {
super.onCreate()
Log.d(TAG, "onCreate: ")
job = GlobalScope.launch {
repeat(20) {
Log.d(TAG, "onStartCommand: $it")
simpleBinder.onListener.invoke(it)
delay(1000)
}
}
}
- MyService中的完整代码
class MyService : Service() {
companion object {
private const val TAG = "MyService"
var starter: Intent? = null
fun start(context: Context) {
if (starter == null){
starter = Intent(context, MyService::class.java)
}
context.startService(starter)
}
fun stop(context: Context) {
starter?.let {
context.stopService(starter)
}
}
}
var job: Job? = null
override fun onCreate() {
super.onCreate()
Log.d(TAG, "onCreate: ")
job = GlobalScope.launch {
repeat(10) {
Log.d(TAG, "onStartCommand: $it")
delay(1000)
}
stop(this@MyService)
//或者使用stopSelf()
}
}
override fun onBind(intent: Intent?): IBinder? {
TODO("Not yet implemented")
}
override fun onDestroy() {
super.onDestroy()
//停止协程
job?.cancel()
Log.d(TAG, "onDestroy: ")
}
}
- 可以看出在stopService后,协程也停止了
D/MyService: onStartCommand: 0
D/MyService: onStartCommand: 1
D/MyService: onStartCommand: 2
D/MyService: onStartCommand: 3
D/MyService: onStartCommand: 4
D/MyService: onDestroy:
- 另外任务完成后,服务销毁
2021-04-06 16:20:00.183 4859-5016/com.vision.mycoroutineservice D/MyService: onStartCommand: 2
2021-04-06 16:20:01.185 4859-5013/com.vision.mycoroutineservice D/MyService: onStartCommand: 3
2021-04-06 16:20:02.188 4859-5013/com.vision.mycoroutineservice D/MyService: onStartCommand: 4
2021-04-06 16:20:03.192 4859-5015/com.vision.mycoroutineservice D/MyService: onStartCommand: 5
2021-04-06 16:20:04.197 4859-5013/com.vision.mycoroutineservice D/MyService: onStartCommand: 6
2021-04-06 16:20:05.200 4859-5013/com.vision.mycoroutineservice D/MyService: onStartCommand: 7
2021-04-06 16:20:06.203 4859-5013/com.vision.mycoroutineservice D/MyService: onStartCommand: 8
2021-04-06 16:20:07.205 4859-5015/com.vision.mycoroutineservice D/MyService: onStartCommand: 9
2021-04-06 16:20:08.219 4859-4859/com.vision.mycoroutineservice D/MyService: onDestroy:
GlobalScope
- GlobalScope的生命周期是application,所以需要手动停止协程
- 关于GlobalScope、lifecycleScope、viewModelScope的用法