6.26 Service笔记

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.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值