IntentService繼承于Service,它的特點是什么呢?就跟龍叔小程序的特點一樣——“用完即走”。
用過IntentService的人都知道,使用非常簡單,根本不用自己去建立線程啊,維護線程通訊啊,甚至連最后資源的釋放也不用我們自己處理,我們只需專心于業務實現即可,也就是編寫onHandleIntent(Intent intent)方法中的代碼,具體使用這里就不多說了,其實我們在之前的文章:定時任務之Alarm,已經使用了IntentService,今天我們主要來分析一下IntentService原理。
分析原理,當然是要看源碼的,我們一步步來看:
@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);
}
啟動一個IntentService,當然先進onCreate方法啦,從上面源碼我們可以看到,第一步我們創建了一個HandlerThread(至于HandlerThread相關的說明,可查看:Handler相關看這篇就夠了),然后啟動線程,獲取Looper,然后將HandlerThread中的Looper與ServiceHandler進行綁定,好啦,我們看看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是一個內部類,繼承于Handler,在handleMessage中我們看到了熟悉的方法:onHandleIntent(Intent intent),哦,原來我們使用IntentService中最重要的覆蓋的onHandleIntent方法是在這里調用的,這里我們說明幾點:
1)因為ServiceHandler是與HandlerThread中的Looper綁定的,所以onHandleIntent方法是在子線程中執行的。
2)我們注意到執行完onHandleIntent后,調用了stopSelf(msg.arg1),這就是為什么IntentService能做到“用完即走”的原因了,因為執行完任務后它會停掉自己的服務。
3)注意:這里自己停掉服務用的是stopSelf(int startId)方法,而不是stopSelf() ,為什么呢?那么我們就得先說一下這兩個API之間的區別了,首先我們看stopSelf() 的源碼:
public final void stopSelf() {
stopSelf(-1);
}
發現原來stopSelf()調用的是stopSelf(int startId),只不過startId為-1而已。
說到這個startId,它是什么呢?其實它就是service的一個生命周期:onStartCommand(@Nullable Intent intent, int flags, int startId)中最后的一個參數。
我們都知道,當我們多次調用startService來啟動同一個service時,只有第一次會執行onCreate,然后會多次調用onStartCommand,如果你去打印log的話,你會發現盡管onCreate只執行一次,但是每次的startId卻是不同的,且都大于0。
而stopSelf(int startId)中的startId與onStartCommand中的startId是一一對應的關系,所以,當我們調用stopSelf(int startId)時,系統會檢測是否還有其它的startId存在,有的話就不銷毀當前service,沒有的話則銷毀。
而如果我們調用的是stopSelf(),那么無論是否還存在其它的startId,都會立即銷毀當前service。
這就是stopSelf()和stopSelf(int startId)兩個方法的區別!
我們回到之前的的問題,為什么IntentService中自停服務用的是stopSelf(int startId)而不是stopSelf()呢?
從上面比較兩個方法的區別我們不能得出:這是為了提高IntentService的利用率,也就是說,如果在onHandleIntent方法執行完畢前,又調用了startService啟動了同一個IntentService,那么我們就沒必要銷毀當前service了,直接繼續用當前service對象執行任務即可,這樣有利于減少了對象的銷毀及創建。
另外:這里插一點,因為IntentService中用的是一個HandlerThread,也就是單一的線程,所以,用IntentService來執行任務只能是串行依次進行。
下面,我們繼續分析源碼,我們剛剛說到了onStartCommand,那我們也來看看它的源碼:
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
onStartCommand第一步調用的是onStart,從onStart方法我們可以看出,其實就是用上面的handler發送了消息,從主線程切換到了子線程執行任務,這個沒什么好說的。
然后我們看下面一行代碼,返回值: mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
查看了一下mRedelivery默認值是false,當然提供了相應的方法可進行設置,下面我們先簡單說明下onStartCommand幾種返回值及區別:
1)START_STICKY:如果service進程被kill掉,保留service的狀態為開始狀態,但不保留遞送的intent對象。隨后系統會嘗試重新創建service,由于服務狀態為開始狀態,所以創建服務后一定會調用onStartCommand(Intent,int,int)方法。如果在此期間沒有任何啟動命令被傳遞到service,那么參數Intent將為null。
2)START_NOT_STICKY:“非粘性的”。使用這個返回值時,如果在執行完onStartCommand后,服務被異常kill掉,系統不會自動重啟該服務
3)START_REDELIVER_INTENT:重傳Intent。使用這個返回值時,如果在執行完onStartCommand后,服務被異常kill掉,系統會自動重啟該服務,并將Intent的值傳入。
4)START_STICKY_COMPATIBILITY:START_STICKY的兼容版本,但不保證服務被kill后一定能重啟。
從上面的介紹我們知道了,onStartCommand默認返回了START_NOT_STICKY,所以,這里注意了,如果你使用IntentService執行的任務非常重要的話,建議通過設置setIntentRedelivery將mRedelivery設置為true,這樣一來onStartCommand的返回就變成了START_REDELIVER_INTENT,有利于異常情況下服務的重啟及恢復。
最后,我來看看銷毀的方法:
@Override
public void onDestroy() {
mServiceLooper.quit();
}
前面我們在Handler相關看這篇就夠了這篇文章中介紹HandlerThread就說了,使用HandlerThread必須注意用完釋放Looper,這不?IntentService在onDestroy生命周期中,幫我們進行了Looper的釋放,所以我們得以“用完即走”,什么都不用處理,超級方便。
好啦,大概也就這些了,別看IntentService的源碼也就一百多行,其實細究起來還是能學到不少東西的。