HandlerThread
HandlerThread继承于THread,它的不同之处是在于可以使用Handler的Thread.
public void run(){
mTid-Process.myTid();
Looper.prepare();
synchronized (this){
mLooper=Looper.myLooper();
notifyA11();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.1oop();
mTid--1;
}
在其实现的run方法中通过Looper.prepare创建了消息队列,通过Looper.loop开启消息循环
HandlerThread与普通Thread的异同
普通的Thread主要就是在子线程中后台执行异步任务,而HandlerThread需要通过Handler消息机制发送消息,在接受到消息后再由消息循环器进行Looper串行处理,去执行指定的任务.
IntentService
IntentService是一种特殊的Service,是一个抽象类需要子类实现才能够使用,另外由于IntentService是服务的原因,所以它的优先级较高,所以它更合适去执行一些优先级较高的后台异步任务,其次另外一点,在每次任务执行完成之后都会自动停止.
IntentService实现原理
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();
mServicelHandler-new ServiceHandler(mServiceLooper);
}
在IntentService第一次启动的时候,会调用onCreate方法,在onCreate方法中,首先会创建创建一个HandlerThread,然后会通过HandlerThread的Looper创建一个Handler,这样一来,就保障了Handler每次发送消息都会发送到HandlerThread中去执行.
public void onstart (Intent intent,int startId){
Measage mag-mServicellandler,obtainMessage();
msg.arg1=startId;
msg.obj=intent;
mServiceHandler.sendMessage(msg);
}
在每次启动IntentService时,其都会调用onStratCommand方法,在omStratComand内部又会调用onStart方法,在onStrat方法中,会通过Handler对象发送消息回Handler中进行处理,在这个过程中,会将Intent一并传递过去;
private final class Servicelandler extends Handler {
public ServiceHandler(Looper looper){
super(looper);
}
@override
public void handleMessage(Message msg){
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}
在handlerMeassage中获取到的Intent和外部调用IntentService投递的Intent内容是完全一样的,所以,onHandlerIntent在处理的时候,可以根据Intent中包含的不同参数来区分所需要执行的不同的后台异步任务.
在onHandlerIntent执行完成之后就会调用stopSelf(stratId id)方法用于停止服务,而之所以没有选用stopSelf()方法是因为,stopSelf()方法会直接停止服务,而stopSelf(stratId id)会首先校对启动次数以及当前传入的ID,当相等的就会停止服务,当不相等则不停止.
其次另外值得说明的一点是,HandlerThread内部的循环是串行执行,IntentService当有多个任务需要执行执行的时候,是会依照调用顺序依次执行.