HandlerThread
它继承了Thread,在它的run方法中创建了Looper并开启了消息循环,这样我们就可以通过获得HandlerThread的Looper来创建Handler,而该handler的任务是执行在该HandlerThread线程中的,就是这样。
HandlerThread的run方法由于开启了Looper,它是一个无限阻塞式循环,因此当明确不需要再使用HandlerThread时,可以通过它的quit或者quitSafely方法来终止线程的执行;
IntentServcie
它是一个特殊的Service,它继承了Servcie并且是一个抽象类,因此必须要创建它的子类才可以使用IntentServcie;
优点:它可用于执行后台耗时任务,当任务执行完成后,它会自动停止service,同时由于它是Service的原因,导致它的优先级比单纯的线程要高的多,所以它比较适合执行一些高优先级的后台任务,因为它不易被系统杀死;
IntentService封装了Handler和HandlerThread,流程如下:
当IntentService第一次被启动时,在onCreate中会创建一个HandlerThread,再通过HandlerThread的Looper创建一个Handler,如下:
public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
IntentService每次启动,都会调用onStartCommand方法,在该方法中处理每个后台任务的intent,该intent会被Message携带,被由发送Handler发送,最终在HandlerThread的线程中被执行;在Handler的handleMessage中,有一个onHandleIntent方法,它需要子类去重写,它是根据不同的后台去做处理;
注意:HandlerThread是在IntentService的onCreate中创建的,当onHandleIntent()方法执行完后,调用stopSelf(startid)来关闭自己,它和stopSelf()的区别是,它不会立即停止服务,因为这个时候可能还有其他信息没有处理完成,stopSelf(startid)会等待所有的消息都处理完毕后才终止服务,也就是说,每执行一个后台任务就必须启动一次IntentService,当所有后台任务执行完成后sevice才会被销毁,但这个HandlerThread和Handler是唯一的,即所有后台任务都在HandlerThread这个线程中执行的,而且Handler中的Looper是顺序处理消息的,意味着IntentServcie也是顺序执行后台任务的,所以,它也不可执行太耗时的任务,容易引起阻塞;
当有多个后台任务时同时存在时,这些后台任务会按照外界发起的顺序排队执行