IntentService是一個帶線程的service,用于處理Intent類型的異步任務請求。當用戶端調用startService(Intent)發送請求時,Service服務被啟動,且在其内部建構一個工作線程來處理Intent請求。當工作線程執行結束,Service服務會自動停止。IntentService繼承于Service,它最大的特點是對服務請求逐個進行處理。當我們要提供的服務不需要同時處理多個請求的時候,可以選擇繼承IntentService。IntentService是一個抽象類,使用者必須實作一個子類去繼承它,且必須至少要實作兩個函數:構造函數和onHandleIntent()函數。
IntentService源碼分析
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.app;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
/**
* IntentService is a base class for {@link Service}s that handle asynchronous
* requests (expressed as {@link Intent}s) on demand. Clients send requests
* through {@link android.content.Context#startService(Intent)} calls; the
* service is started as needed, handles each Intent in turn using a worker
* thread, and stops itself when it runs out of work.
*
* <p>This "work queue processor" pattern is commonly used to offload tasks
* from an application's main thread. The IntentService class exists to
* simplify this pattern and take care of the mechanics. To use it, extend
* IntentService and implement {@link #onHandleIntent(Intent)}. IntentService
* will receive the Intents, launch a worker thread, and stop the service as
* appropriate.
*
* <p>All requests are handled on a single worker thread -- they may take as
* long as necessary (and will not block the application's main loop), but
* only one request will be processed at a time.
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For a detailed discussion about how to create services, read the
* <a href="{@docRoot}guide/topics/fundamentals/services.html" target="_blank" rel="external nofollow" >Services</a> developer guide.</p>
* </div>
*
* @see android.os.AsyncTask
*/
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
/*ServiceHandler是IntentService的内部類,繼承自Handler,在重寫消息處理方法handlerMessage裡面調用了onHandlerIntent
抽象方法去處理異步任務intent的請求,當異步任務請求結束之後,調用stopSelf方法自動結束IntentService服務。此處handleMessage
方法是在工作線程中調用的,是以我們子類重寫的onHandlerIntent
也是在工作線程中實作的。
*/
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);
}
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
//IntentService構造方法,參數name用于定義工作線程的名稱
public IntentService(String name) {
super();
mName = name;
}
/**
* Sets intent redelivery preferences. Usually called from the constructor
* with your preferred semantics.
*
* <p>If enabled is true,
* {@link #onStartCommand(Intent, int, int)} will return
* {@link Service#START_REDELIVER_INTENT}, so if this process dies before
* {@link #onHandleIntent(Intent)} returns, the process will be restarted
* and the intent redelivered. If multiple Intents have been sent, only
* the most recent one is guaranteed to be redelivered.
*
* <p>If enabled is false (the default),
* {@link #onStartCommand(Intent, int, int)} will return
* {@link Service#START_NOT_STICKY}, and if the process dies, the Intent
* dies along with it.
*/
public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
}
//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.
//利用HandlerThread類建立了一個循環的工作線程thread,然後将工作線程中的Looper對象作為參數來建立
ServiceHandler消息執行者。
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
/*該方法中通過mServiceHandler獲得一個消息對象msg,然後将startId作為該消息的消息碼,将異步任務請求intent作為
消息内容封裝成一個消息msg發送到mServiceHandler消息執行者中去處理.*/
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
/**
* You should not override this method for your IntentService. Instead,
* override {@link #onHandleIntent}, which the system calls when the IntentService
* receives a start request.
* @see android.app.Service#onStartCommand
*/
//Service服務生命周期第二步執行onStartCommand方法。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
/* 該方法中調用HandlerThread工作線程中Looper對象的quit方法讓目前工作線程HandlerThread退出目前Looper循環,進而結束線程。
進而結束目前IntentService服務。
*/
@Override
public void onDestroy() {
mServiceLooper.quit();
}
/**
* Unless you provide binding for your service, you don't need to implement this
* method, because the default implementation returns null.
* @see android.app.Service#onBind
*/
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* This method is invoked on the worker thread with a request to process.
* Only one Intent is processed at a time, but the processing happens on a
* worker thread that runs independently from other application logic.
* So, if this code takes a long time, it will hold up other requests to
* the same IntentService, but it will not hold up anything else.
* When all requests have been handled, the IntentService stops itself,
* so you should not call {@link #stopSelf}.
*
* @param intent The value passed to {@link
* android.content.Context#startService(Intent)}.
*/
/* 該方法用于處理intent異步任務請求,在工作線程中調用該方法。每一個時刻隻能處理一個intent請求,當同時又多個intent請求時,
也就是用戶端下一個intent請求。直到所有的intent請求結束之後,IntentService服務會調用stopSelf停止目前服務。
也就是當intent異步任務處理結束之後,對應的IntentService服務會自動銷毀
*/
protected abstract void onHandleIntent(Intent intent);
}
可以看出來,IntentService的核心就是HandlerThread源碼分析,HandlerThread+Handler建構成了一個帶有消息循環機制的異步任務處理機制。隻要搞明白了HandlerThread,自然而然就明白IntentService了。
IntentService總結
IntentService有以下特點:
(1) 它建立了一個獨立的工作線程來處理所有的通過onStartCommand()傳遞給服務的intents。
(2) 建立了一個工作隊列,來逐個發送intent給onHandleIntent()。
(3) 不需要主動調用stopSelft()來結束服務。因為,在所有的intent被處理完後,系統會自動關閉服務。
(4) 預設實作的onBind()傳回null
(5) 預設實作的onStartCommand()的目的是将intent插入到工作隊列中。
隻要我們的Service繼承IntentService,實作onHandleIntent()就可以工作在非主線程,而且還不用擔心并發,不用擔心關閉service等問題。
IntentService類内部利用HandlerThread+Handler建構了一個帶有消息循環處理機制的背景工作線程,這是一個單線程來處理異步任務。用戶端隻需調用startService(Intent)将Intent任務請求放入背景工作隊列中。隻要目前IntentService服務沒有被銷毀,用戶端就可以同時投放多個Intent異步任務請求,IntentService服務端這邊是順序執行目前背景工作隊列中的Intent請求的,也就是每一時刻隻能執行一個Intent請求,直到該Intent處理結束才處理下一個Intent。