1 概論
IntentService是一種處理異步請(qǐng)求的Service袁波∠砘常客戶(hù)端通過(guò)調(diào)用Context.startService(Intent)
來(lái)發(fā)送請(qǐng)求位他,啟動(dòng)Service卿城;Service按需啟動(dòng)后柬帕,會(huì)依次按順序處理工作線(xiàn)程中的Intent哟忍,并且在工作結(jié)束后會(huì)自動(dòng)停止狡门。
2 IntentService是如何啟動(dòng)一個(gè)異步線(xiàn)程處理請(qǐng)求的?
IntentService在創(chuàng)建時(shí)锅很,會(huì)創(chuàng)建并啟動(dòng)一個(gè)線(xiàn)程HandlerThread其馏,并且賦予這個(gè)線(xiàn)程一個(gè)Looper;
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
ServiceHandler是Handler的一個(gè)子類(lèi),用來(lái)接受處理消息Message爆安,我們知道一般Handler是在UI主線(xiàn)程接受處理消息的叛复,要想在異步線(xiàn)程接受處理消息,必須給這個(gè)異步線(xiàn)程關(guān)聯(lián)一個(gè)Looper扔仓,并且在異步線(xiàn)程調(diào)用Looper.prepare()方法褐奥;
public class HandlerThread extends Thread {
int mPriority;
int mTid = -1;
Looper mLooper;
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
...
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
...
}
3 IntentService是如何處理Intent的
調(diào)用Context.startService(Intent)后,Service被啟動(dòng)翘簇,執(zhí)行onCreate()方法撬码,然后執(zhí)行onStart(Intent intent,int startId);
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
可以看到Service開(kāi)始后,會(huì)把Intent對(duì)象通過(guò)Handler機(jī)制交給ServiceHandler來(lái)處理版保,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);
}
}
ServiceHandler接受到消息后呜笑,取出Intent,啟動(dòng)onHandleIntent(Intent) 方法彻犁,來(lái)處理Intent叫胁;
我們來(lái)看onHandleIntent(Intent intent);
protected abstract void onHandleIntent(Intent intent);
這是一個(gè)抽象方法,留給開(kāi)發(fā)者自己實(shí)現(xiàn)袖裕,異步操作的實(shí)現(xiàn)邏輯都在這個(gè)抽象方法里面曹抬;操作完成后,通過(guò)調(diào)用stopSelf()
Service
4 總結(jié)
- IntentService在創(chuàng)建的時(shí)候會(huì)創(chuàng)建一個(gè)線(xiàn)程急鳄,并啟動(dòng)這個(gè)異步線(xiàn)程;
- 創(chuàng)建的異步線(xiàn)程會(huì)利用Looper堰酿、Handler來(lái)創(chuàng)建疾宏、發(fā)送、接受消息Message触创,與UI主線(xiàn)程通過(guò)Handler機(jī)制進(jìn)行線(xiàn)程通信是同理的坎藐;
- Service的異步操作邏輯是定義在抽象方法onHandleIntent(Intent)里面,開(kāi)發(fā)者需要實(shí)現(xiàn)這個(gè)抽象方法哼绑;
- ServiceHandler處理消息是在異步線(xiàn)程里面的岩馍,onHandleIntent(Intent)也是運(yùn)行在異步線(xiàn)程里面的,這與UI主線(xiàn)程里面的Handler不同抖韩;