IntentService
Service中的代码都是默认在 主线程 运行, 碰到耗时的 Work ,很容易ANR——Application Not Responding,应用无响应。
此时使用多线程技术,恰到好处。在Service中具体的方法中开一个“处理耗时Work”的 子线程 即可。
class MyService:Service(){
override fun OnStartCommand(intent:Intent,flags:Int,startId:Int):Int{
thread{
//在这里执行耗时Work
}
return super.O nStartCommand(intent,flags,startId)
}
}
IS启动后会一直运行,直到调用stopService()/stopSelf()/被系统回收。如下:
class MyService:Service(){
override fun OnStartCommand(intent:Intent,flags:Int,startId:Int):Int{
thread{
//在这里执行耗时Work
stopSelf()
}
return super.O nStartCommand(intent,flags,startId)
}
}
以上写法简单,但是仍有人忘记开线程或者停止Service,所以有了IntentService。
here,we can new a class named “MyIntentService”,extented from class “IntentService” and called Parent constructor passed in a parameter “MyIntentService”.Then,implements onHandleIntent(intent:Intent?){
Log.d(“MyIntentService”,“Thread is a ${Thread.currentThread().name}”)
} ,where you can process time-consuming work and need not worry about ANR,because this method has been running in subThread.
finally,it will end Service automatically after Service run over.