前言
最近用到了IntentService,相比Service感觉在某些情况下很方便,本篇文章主要对比两者的区别,以及IntentService的使用
比较
Service
Service 是长期运行在后台的应用程序组件。
Service 不是一个单独的进程,它和应用程序在同一个进程中,Service 也不是一个线程,它和线程没有任何关系,所以它不能直接处理耗时操作。如果直接把耗时操作放在 Service 的 onStartCommand() 中,很容易引起 ANR.如果有耗时操作就必须开启一个单独的线程来处理。
IntentService
send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
This “work queue processor” pattern is commonly used to offload tasks from an application’s main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
All requests are handled on a single worker thread – they may take as long as necessary (and will not block the application’s main loop), but only one request will be processed at a time.
IntentService是Service的子类,根据需要处理异步请求(以intent表示)。客户端通过调用startService(Intent) 发送请求,该Service根据需要启动,使用工作线程处理依次每个Intent,并在停止工作时停止自身。
这种“工作队列处理器”模式通常用于从应用程序的主线程中卸载任务。 IntentService类的存在是为了简化这种模式。 要使用它,扩展IntentService并实现onHandleIntent(Intent)。 IntentService将收到Intents,启动一个工作线程,并根据需要停止该服务。
所有请求都在单个工作线程处理
- 它们可能需要很长的时间(并且不会阻止应用程序的主循环),但是一次只会处理一个请求。
对比Service,IntentService显得更智能:
- 省去了在 Service中手动开线程的麻烦。
- 当操作完成时,我们不用手动停止Service。
使用
- 继承IntentService。
- 实现不带参数的构造方法,并且调用父类IntentService的构造方法。
- 实现onHandleIntent方法
在实际的程序开发中,我们往往需要集成很多第三方,通常都是在Application中进行初始化,这种情况下会花费几秒的时间,从Application的oncreate执行完毕在到启动页执行会有”明显”的延迟(一般启动页都会定个2~3秒再进行跳转),这时候我们就可以考虑将这些初始化操作放到自定义的IntentService类里执行。
class MyService : IntentService("") {
override fun onHandleIntent(intent: Intent?) {
if (intent != null && ACTION_INIT_WHEN_APP_CREATE == intent.action) {
//这里进行第三方sdk的初始化操作
LogUtil.e("初始化完成")
}
}
companion object {
const val ACTION_INIT_WHEN_APP_CREATE = "com.demo.app.create"
fun start(context: Context) {
val intent = Intent(context, MyService::class.java)
intent.action = ACTION_INIT_WHEN_APP_CREATE
context.startService(intent)
}
}
}
然后,在Application类中进行调用:
class DemoApp:Application() {
override fun onCreate() {
super.onCreate()
MyService.start(this)
}
}
结语
IntentService使用起来还是比较便捷的,但是,并不是所有场合都可以用IntentService,IntentService的工作队列有序执行,不能有针对的去取消某个任务。