在说intentservice之前我们先来了解一下handlerthread,handlerthread其实我们平时很少见,但是安卓中应用的还挺多的,他其实也是一个线程,只不过普通的线程逻辑代码是在run方法中执行的,而他的run方法其实是初始化了一个消息队列,并开启消息循环,他的逻辑代码处理是通过handler发送消息来处理的,但是handlerthread的run方法无限循环的,因此当不使用的时候一定记得使用quit方法来终止它。
public void run(){ public Looper mlooper; Looper.prepare(); synchronized (this){ mlooper = Looper.myLooper(); notifyAll(); } onLooperPrePared(); Looper.loop(); 这是其源代码的一部分,
IntentService是一种特殊的service,由于他是安卓中的服务,所以优先级高于线程,适合做一些后台的高优先级的耗时操作,
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler =
new
ServiceHandler(mServiceLooper); }
可见其在oncreat方法中创建了一个handlerthread,然后启动线程拿到了looper循环器,然后把循环器和handler关联起来,这样通过serviehandler发送过来的任务都会在handlerthread执行,每当我们启动service时他的onstartcommand()方法都会调用一次,
public
int
onStartCommand(Intent
intent, int
flags, int
startId)
{
onStart(intent,
startId);
return
mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
其调用了onstart()方法;
public
void
onStart(Intent
intent, int
startId)
{
Message
msg = mServiceHandler.obtainMessage();
msg.arg1
= startId;
msg.obj
= intent;
mServiceHandler.sendMessage(msg);
}
onstart中拿到handler发送过来的任务,在handlermessage中执行,这样任务就是在handlerthread中执行的,而handlermessage()方法中又调用了onHnadlerIntent()方法,所以就保证了我们可以直接在这个方法中进行任务处理,不需要自己去new线程,而且每执行完成一个任务,会相应
的终止刚刚完成的任务,当service中没有任务时,service停止,
还有一点就是intentrservice中的任务时按顺序执行的,因为handler的消息机制是按顺序接受的,所以任务执行也是按顺序执行的。