一、简介
IntentService是一种特殊的Service,它可以进行一些后台的耗时操作,在任务执行结束后会自动停止。由于它是一种服务,所以它的优先级要高于普通的线程,不容易被系统杀死。
内部封装了HandlerThread 和 Handler
二,使用
1、创建IntentService的子类,实现onHandleIntent(@Nullable Intent intent)方法和构造方法
2、在Activity中使用Intent启动服务
Intent mService = new Intent(this,TestIntentService.class);
startService(mService);//可以启动多次
3、 在onHandleIntent中使用传递过来的intent获取值,比如URL。接下来就可以使用URL去做一些耗时操作
4、最后使用发送广播sendBroadcast的形式将结果回传给Activity
三,源码分析
1、onCreate()
IntentService在创建的时候onCreate()方法中会创建一个HandlerThread thread对象,并调用thread.start()启动该线程。调用该HandlerThread的getLooper方法获取到Looper对象:
mServiceLooper = thread.getLooper();
使用mServiceLooper创建Handler对象:
mServiceHandler = new ServiceHandler(mServiceLooper);使得该handler运行在子线程中
2、onStartCommand()
IntentService在onCreate()方法之后会调用onStartCommand方法,在该方法中会调用onStart()方法
3、onStart()
onStart方法中只是使用handler对象的mServiceHandler发送了一条消息
4、ServiceHandler
handler接受到消息后直接调用onHandleIntent方法,由于handler运行在子线程,所以onHandleIntent也是运行在子线程中,所以可以在其中做耗时操作
onHandleIntent执行完成后会调用stopSelf()方法停止服务
5、onDestroy()
在退出服务的时候会调用mServiceLooper.quit()退出Looper
注意:从源码可以看到IntentService内部是使用Handler消息传递处理消息的,是顺序处理消息,这就意味着IntentService也是顺序执行后台任务的。所以当启动多个服务时,这些后台任务是按照顺序的方式来执行的