IntentService 使用與源碼解析
IntentService 這兄弟用的地方也蠻多,用起來也蠻順手, 而且用過不用太操心是否將其關閉。 之前在介紹Handler消息機制一文中簡單介紹其工作原理。 本文就着重IntentService進行解析。
本文主要分六部分展開:
- IntentService的介紹
- IntentService的使用
- IntentService的源碼解析
- IntentService的常見問題
- 總結
- 參考資料
1. IntentService的介紹
這麼說吧如果有一個任務,可以分成很多個子任務,需要按照順序來完成,如果需要放到一個服務中完成,那麼使用IntentService是最好的選擇。
一般情況下我們所使用的Service是運行在主線程當中的,所以在service裏面編寫耗時的操作代碼,則會卡主線程會ANR。爲了解決這樣的問題,谷歌引入了IntentService.
IntentService是自己維護了一個線程,來執行耗時的操作,然後裏面封裝了HandlerThread,能夠方便在子線程創建Handler。
IntentService是繼承自Service用來處理異步請求的一個基類,客戶端startService發送請求,IntentService就被啓動,然後會在一個工作線程中處理傳遞過來的Intent,當任務結束後就會自動停止服務。
2. IntentService的使用
IntentService的使用十分簡單,分爲下面幾個步驟:
- 新建子類繼承IntentService,在AndroidManifest註冊該Service, 複寫onHandleIntent方法並在onHandleintent方法中進行異步操作
- 一般在Activity中調用IntentService,與使用普通Service類似,不過不要使用綁定方式,而要使用startService啓動,並在Intent中放入相應的數據
- 使用Handler或者本地廣播等手段將onHandleIntent異步執行結果傳給主線程
- 主線程獲取到異步操作結果並對其進行處理和展示等等
具體的使用方法就不粘貼了, 網上代碼一搜一大把。
3. IntentService的源碼解析
源碼解析, 鑑於 IntentService 一共也沒多少行,索性都粘出來 。
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
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.
*/
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.
*
從字面理解是設置intent重投遞。如果設置爲true,
onStartCommand(Intent, int, int)將會返回START_REDELIVER_INTENT,
如果onHandleIntent(Intent)返回之前進程死掉了,那麼進程將會重新啓動,intent重新投遞,
如果有大量的intent投遞了,那麼只保證最近的intent會被重投遞。
*/
public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
}
/// Service的onCreate 被調用時 即創建 handlerThread , 將HandlerThread的Looper 與ServiceHandler關聯。
//// 至此 ServiceHandler 與異步的子線程HandlerThread 便綁在了一起。 也爲後面的有序執行任務做下了鋪墊, 可謂設計精妙。
@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);
}
@Override
public void onStart(@Nullable 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
* 啓動 除了第一次 調用onCreate 方法 關聯HandlerThread 與ServiceHandler . 其後 再次調用 則會調用onStartCommand 方法 。
該方法 內部會調用onStart方法 。 而同時會把startID傳遞進入Message ,將Intent 作爲 message之obj 包裝後 發送 。
IntentService 是一種non-sticky 服務,non-sticky 服務在服務自己認爲完成任務時停止,爲了獲得non-sticky 服務,應返回 START_REDELIVER_INTENT 或者 START_NOT_STICKY,而二者的區別則是如果系統需要在服務完成任務之前關閉它,則服務的具體表現不同,START_NOT_STICKY會被關閉,而START_REDELIVER_INTENT則會在系統可用資源不喫緊時,嘗試再次啓動。
*/
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
/// Looper quit 之後 該Looper便停止 循環。 同時Service銷燬。
@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
@Nullable
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)}.
* This may be null if the service is being restarted after
* its process has gone away; see
* {@link android.app.Service#onStartCommand}
* for details.
當在onStart方法中,通過sendMessage方法將Message放入到Handler所關聯的消息隊列中後,Handler所關聯的Looper對象會從消息隊列中取出一個Message,然後將其傳入Handler的handleMessage方法中,在handleMessage方法中首先通過Message的obj獲取到了原始的Intent對象,然後將其作爲參數傳給了onHandleIntent方法讓其執行。
handleMessage方法是運行在HandlerThread的,所以onHandleIntent也是運行在工作線程中的。
在執行完了onHandleIntent之後,我們需要調用stopSelf(startId)聲明某個job完成了。
當所有job完成的時候,Android就會回調onDestroy方法,銷燬IntentService。
*/
@WorkerThread /////// 該方法爲工作線程 也就是再HandlerThread中被調用。
protected abstract void onHandleIntent(@Nullable Intent intent);
}
HandlerThread的源碼解析就不再贅述了, 如有想要深入瞭解的可查看我的另一篇文章 Android Handler消息機制解析中的HandlerThread 部分。 算了再簡單把註釋粘一下。
public class HandlerThread extends Thread {
//線程優先級
int mPriority;
int mTid = -1;
Looper mLooper;
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
public HandlerThread(String name, int priority) {
super(name);
mPriority = priority;
}
protected void onLooperPrepared() {
}
@Override
public void run() {
//獲取進程ID
mTid = Process.myTid();
//Loopr準備
Looper.prepare();
//創建Looper
synchronized (this) {
mLooper = Looper.myLooper();
//喚醒所有等待的線程
notifyAll();
}
//設置線程優先級
Process.setThreadPriority(mPriority);
//在Looper循環時做一些準備工作
onLooperPrepared();
//開啓循環
Looper.loop();
mTid = -1;
}
public Looper getLooper() {
//如果線程已經消亡,就返回null
if (!isAlive()) {
return null;
}
//如果線程已經創建了,就在此處停留等待Looper創建完成之後
synchronized (this) {
while (isAlive() && mLooper == null) {
//等待線程被創建
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
public boolean quit() {
//獲取looper
Looper looper = getLooper();
if (looper != null) {
//退出looper
looper.quit();
return true;
}
return false;
}
//安全退出
//跟quit方法的唯一區別在於looper.quit()變成了looper.quitSafely()
public boolean quitSafely() {
Looper looper = getLooper();
if (looper != null) {
looper.quitSafely();
return true;
}
return false;
}
/**
* Returns the identifier of this thread. See Process.myTid().
*/
public int getThreadId() {
return mTid;
}
}
4. IntentService的常見問題
a. 如果啓動IntentService多次,會出現什麼情況呢?
IntentService多次被啓動,那麼onCreate()方法只會調用一次,所以只會創建一個工作線程。但是會調用多次onStartCommand方法,只是把消息加入消息隊列中等待執行
b. 多次開啓intentService,那爲什麼工作任務隊列是順序執行的?
當我們通過startService多次啓動了IntentService,這會產生多個job,由於IntentService只持有一個工作線程,所以每次onHandleIntent只能處理一個job。面多多個job,IntentService會如何處理?處理方式是one-by-one,也就是一個一個按照先後順序處理,先將intent1傳入onHandleIntent,讓其完成job1,然後將intent2傳入onHandleIntent,讓其完成job2…這樣直至所有job完成,所以我們IntentService不能並行的執行多個job,只能一個一個的按照先後順序完成,當所有job完成的時候IntentService就銷燬了,會執行onDestroy回調方法。
5. 總結
IntentService的優點
- 它創建一個獨立的工作線程來處理所有一個一個intent。
- 創建了一個工作隊列,來逐個發送intent給onHandleIntent()
- 不需要主動調用stopSelf()來結束服務,因爲源碼裏面自己實現了自動關閉。
- 默認實現了onBind()返回的null。
- 默認實現的onStartCommand()的目的是將intent插入到工作隊列。
IntentService使用場景
- IntentService不需要我們自己去關閉Service,它自己會在任務完成之後自行關閉,不過每次只能處理一個任務,所以不適用於高併發,適用於請求數較少的情況。
類似於APP的版本檢測更新、 定位功能、同步通訊錄、 筆記應用的筆記列表 資源同步以及 讀取少量的IO操作。 - 推送Service 例如 阿里的推送Service就是 集成自IntentService 。
- 還可以將 應用的初始化, 例如MultiDex中dex的異步加載, 資源文件的異步加載等。