一、为什么要重写onHandleIntent方法?
public abstract class IntentService extends Service {
IntentService也是继承于Service,而Service生命周期无外乎onCreate,onStart,onDestory,所以我们先来看看这几个生命周期方法的实现
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的线程,其run方法如下所示:
public void run() { mTid = Process.myTid(); Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; }
该方法主要是获得一个looper对象,这也是其和Thread最本质的区别,得到Looper对象后会唤醒等待此Looper对象的所有线程,等待Looper的代码如下所示:
/** * This method returns the Looper associated with this thread. If this thread not been started * or for any reason is isAlive() returns false, this method will return null. If this thread * has been started, this method will block until the looper has been initialized. * @return The 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; }
如果该线程已经启动并且还没有创建Looper时就一直等待
之后,IntentService将handlerthread中的Looper传给ServiceHandler对象:
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); } }
接着看onStart方法:
@Override public void onStart(Intent intent, int startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); }
主要是将message对象发送给ServiceHandler,然后ServiceHandler会调用handleMessage进行处理
@Override public void handleMessage(Message msg) { onHandleIntent((Intent)msg.obj); stopSelf(msg.arg1); }
如上所示,调用了一个onHandleIntent方法进行处理,故在我们自己的IntentService中要实现onHandleIntent方法
最后看onDestory方法
@Override public void onDestroy() { mServiceLooper.quit(); }
调用Looper对象的quit方法
public void quit() { Message msg = Message.obtain(); // NOTE: By enqueueing directly into the message queue, the // message is left with a null target. This is how we know it is // a quit message. mQueue.enqueueMessage(msg, 0); }