主目錄見:Android高級(jí)進(jìn)階知識(shí)(這是總目錄索引)
[written by Ticoo]
IntentService跟ThreadHandler一樣,也是Google為了方便開發(fā)者使用Service封裝的一個(gè)類胯盯。
特點(diǎn)
- 通過Context的startService(Intent)溅漾,創(chuàng)建一個(gè)工作線程處理異步請(qǐng)求
- 異步的山叮,串行處理每個(gè)Intent請(qǐng)求,處理完后自行停止Service
不瞎bb了添履,源碼能解釋一下
源碼分析
先看一下構(gòu)造和成員屬性屁倔,
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public IntentService(String name) {
super();
mName = name;
}
IntentService繼承Service,被聲明為 abstract class, 所以我們只能繼承該類暮胧,不能直接使用锐借。
有幾個(gè)比較重要的成員屬性Looper和ServiceHandler问麸。Looper的作用我們就不啰嗦了,前面的文章已經(jīng)介紹過了瞎饲。
ServiceHandler是IntentService里的一個(gè)內(nèi)部類口叙,繼承Handler,實(shí)際用來處理Intent請(qǐng)求的方式嗅战。子類重寫onHandleIntent(Intent)處理Intent妄田,之后調(diào)用stopSelf停止Service。
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);
}
}
沒錯(cuò)驮捍,聰明的你看到這里也大致猜到了疟呐,IntentSeries內(nèi)部其實(shí)就是使用Handler,Looper的機(jī)制东且,異步處理Intent請(qǐng)求的启具。不過,我們還得繼續(xù)分析源碼珊泳,因?yàn)檫€有內(nèi)容值得我們學(xué)習(xí)鲁冯。
按Service的生命周期來看,會(huì)先調(diào)用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);
}
這里創(chuàng)建了一個(gè)HandlerThread和一個(gè)ServiceHandler色查,并將HandlerThread里的Looper傳給ServiceHandler薯演,是不是挺熟悉的? 恩秧了,就是我們上個(gè)章節(jié)對(duì)HandlerThread的介紹里面的內(nèi)容跨扮,這里就不多廢話了。
接下來我們繼續(xù)看 onStart验毡,onStartCommand方法
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
最終調(diào)用的是onStart方法衡创, 從mServiceHandler里obtain一條Message, 將startId和Intent通過Handler傳遞給Looper晶通,MessageQueue璃氢。 根據(jù)Handler的機(jī)制處理消息,在IntentService destroy的時(shí)候也將Looper停止狮辽。
@Override
public void onDestroy() {
mServiceLooper.quit();
}
所以一也,我們?cè)谑褂肐ntentService的時(shí)候,只需要繼承IntentService隘竭,并重寫onHandleIntent方法,在需要的使用通過Content startService發(fā)送一個(gè)異步請(qǐng)求就可以了讼渊。