IntentService簡介
是一種特殊的Service,繼承了Service並且是個抽象類,可用於執行後臺耗時任務,當任務結束後自動停止,同時由於是服務的原因,它的優先級比普通線程高很多,因此不容易被系統殺死。在實現上,IntentService封裝了HandlerThread和Handler。
基本流程
startService(intentService):
onCreate()->
onStartCommand()->
onStart()->
sendMessage()->
handlerMessage()->
onHandlerIntent()->
stopSelf(startId)->
onDestroy->
詳細解剖
onCreate()
當服務第一次創建的時候調用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 和 Handler
onStartCommand()
每一次啓動服務的時候調用onStartCommand()
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
該方法僅僅調用了onStart()方法
onStart()
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
該方法把startService傳來的Intent和startId封裝成Message消息,然後通過handler發送消息,接着執行mServiceHandler.handleMessage()
其中ServiceHandler是IntentService的一個內部類,它的定義如下
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);
}
}
handleMessage()
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
該方法會執行onHandleIntent()方法,它是個抽象方法,因此我們自定義IntentService的時候必須重寫onHandleIntent()方法。因爲發送消息那那個handler是HandlerThread所關聯的,所以處理信息的時候是在子線程進行的。不會的可以看看HandlerThread原理。
stopSelf()
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
當onHandleIntent()方法執行完畢之後,會調用stopSelf(int)方法結束服務
onDestroy()
@Override
public void onDestroy() {
mServiceLooper.quit();
}
最後銷燬服務的時候,終止線程執行