IntentService源码分析
1.简介
IntentService继承Service,同其他Service一样,如果start方式启动多次的话,生命周期执行顺序为:onCreate()->onStartCommand()->onStart()>onStartCommand()->onStart()->...onDestory()
IntentService适合用于异步任务,它运行于一个单独的线程中,在onHandleIntent()中处理异步任务
如果多次启动IntentService,那么异步任务会以队列的形式,串行执行
所有的IntentService任务执行完毕,会自动停掉Service
2.源码分析
首先创建IntentService,会调用onCreate()
@Override 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); }
HandlerThread继承Thread,可以知道是一个线程类,看HandlerThread的run方法
@Override public void run() { mTid = Process.myTid(); Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; }
主要创建了一个Looper,该Looper在子线程中,
public Looper getLooper() { if (!isAlive()) { return null; } // If the thread has been started, wait until the looper has been created. synchronized (this) { while (isAlive() && mLooper == null) { try { wait(); } catch (InterruptedException e) { } } } return mLooper; }
看synchronized块,当线程处于运行状态,并且mLooper为null是,该线程会处于等待状态,如果run()中执行了notifyAll()则等待结束
mServiceLooper是一个子线程的Looper,所以IntentService可以处理子任务
start启动Service,会调用onStartCommand()
@Override public int onStartCommand(Intent intent, int flags, int startId) { onStart(intent, startId); return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY; }
接着调用了onStart()
@Override public void onStart(Intent intent, int startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); }
可以看出,任务都是发送给mServiceHandler处理
private volatile ServiceHandler mServiceHandler;
private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { onHandleIntent((Intent)msg.obj); stopSelf(msg.arg1); } }
这里就明白了了,为什么IntentService多次启动时,任务是串行执行的,因为是以Message的形式发送给ServiceHandler,Handler以队列的形式处理消息,然后调用onHandleIntent()处理任务,最后调用stopSelf(),当任务结束后调用stopSelf()
public final void stopSelf(int startId) { if (mActivityManager == null) { return; } try { mActivityManager.stopServiceToken( new ComponentName(this, mClassName), mToken, startId); } catch (RemoteException ex) { } }需要注意一点,stopSelf()会等到所有任务都执行完毕之后,才会停掉Service