Android IntentService詳解

轉載請注明出處:http://www.lxweimin.com/p/95e0ef1b81cb
最近正在加深基礎,看到個IntentService類,以前從來沒有遇見過,更不知其用來干嘛的,所以就整理了一個demo,看看這個怎么使用。
我們經常用到Service,并且在Service開啟線程處理耗時操作,Android封裝了一個IntentService類,該類已經幫我們創建好了線程供我們使用。


1 簡介

IntentService概括

IntentService is a base class for Service that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through 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.
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 onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
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.

IntentService是Service的子類,根據需要處理異步請求(以intent表示)。客戶端通過調用startService(Intent) 發送請求,該Service根據需要啟動,使用工作線程處理依次每個Intent,并在停止工作時停止自身。
這種“工作隊列處理器”模式通常用于從應用程序的主線程中卸載任務。 IntentService類的存在是為了簡化這種模式。 要使用它,擴展IntentService并實現onHandleIntent(Intent)。 IntentService將收到Intents,啟動一個工作線程,并根據需要停止該服務。
所有請求都在單個工作線程處理 - 它們可能需要很長的時間(并且不會阻止應用程序的主循環),但是一次只會處理一個請求。


2 代碼

在IntentService中處理下載請求(模擬),并將進度更新到Ui。
MyIntentService.java代碼如下:

public class MyIntentService extends IntentService {
    private final static String TAG = "MyIntentService";
    
    public static final String ACTION_DOWN_IMG = "down.image";
    public static final String ACTION_DOWN_VID = "down.vid";
    public static final String ACTION_DOWN_PROGRESS = "com.zpengyong.down.progress";
    public static final String ACTION_SERVICE_STATE = "com.zpengyong.service.state";    
    public static final String PROGRESS = "progress";
    public static final String SERVICE_STATE = "service_state";

    //構造方法 一定要實現此方法否則Service運行出錯。
    public MyIntentService() {
        super("MyIntentService");
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");
        sendServiceState("onCreate");
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.i(TAG, "");
    }
    
    @Override
    protected void onHandleIntent(Intent intent) {
        Log.i(TAG, "onHandleIntent thread:"+Thread.currentThread());
        String action = intent.getAction();
        if(action.equals(ACTION_DOWN_IMG)){
            for(int i = 0; i < 100; i++){
                try{ //模擬耗時操作
                    Thread.sleep(50);
                }catch (Exception e) {
                }
                sendProgress(i);
            }
        }else if(action.equals(ACTION_DOWN_VID)){
            for(int i = 0; i < 100; i++){
                try{ //模擬耗時操作
                    Thread.sleep(70);
                }catch (Exception e) {
                }
                sendProgress(i);
            }
        }
        Log.i(TAG, "onHandleIntent end");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy");
        sendServiceState("onDestroy");
    }
    //發送Service的狀態
    private void sendServiceState(String state){
        Intent intent = new Intent();
        intent.setAction(ACTION_SERVICE_STATE);
        intent.putExtra(SERVICE_STATE, state);
        sendBroadcast(intent);
    }
    
    //發送進度
    private void sendProgress(int progress){
        Intent intent = new Intent();
        intent.setAction(ACTION_DOWN_PROGRESS);
        intent.putExtra(PROGRESS, progress);
        sendBroadcast(intent);
    }
}

使用IntentService的方法:

  1. 繼承IntentService。
  2. 實現不帶參數的構造方法,并且調用父類IntentService的構造方法。
  3. 實現onHandleIntent方法。

在onHandleIntent方法中可以根據intent來區分任務,這里有兩個任務,一個是下載圖片、一個是下載視頻(模擬耗時操作)。
運行效果
1 只點擊“啟動任務一”。

啟動任務一

打印:

07-15 03:07:24.589: I/MyIntentService(3186): onCreate
07-15 03:07:24.593: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:07:30.918: I/MyIntentService(3186): onHandleIntent end
07-15 03:07:31.017: I/MyIntentService(3186): onDestroy

IntentService啟動后再onHandleIntent方法中執行任務(該方法工作在子線程中),任務執行完后,IntentService銷毀。

2 點擊“啟動任務一”,任務未完成時點擊“停止Service”。

停止Service

log

07-15 03:08:08.477: I/MyIntentService(3186): onCreate
07-15 03:08:08.478: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:08:12.203: I/MyIntentService(3186): onDestroy
07-15 03:08:14.253: I/MyIntentService(3186): onHandleIntent end

IntentService中線程執行任務時,stopService會讓IntentService銷毀,但是任務繼續執行,直到執行完成線程退出。

3 點擊“啟動任務一”,任務完成后點擊“啟動任務二”。

任務完成再啟動

log信息:

07-15 03:11:42.366: I/MyIntentService(3186): onCreate
07-15 03:11:42.367: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:11:48.285: I/MyIntentService(3186): onHandleIntent end
07-15 03:11:48.289: I/MyIntentService(3186): onDestroy
07-15 03:11:50.174: I/MyIntentService(3186): onCreate
07-15 03:11:50.205: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:11:58.446: I/MyIntentService(3186): onHandleIntent end
07-15 03:11:58.510: I/MyIntentService(3186): onDestroy

由上可知,任務執行完成后,線程退出循環,Service銷毀。重新開啟任務則重新創建Service,執行任務。

4 點擊“啟動任務一”,任務完成前點擊“啟動任務二”。

啟動兩個任務

log信息

07-15 03:16:46.998: I/MyIntentService(3186): onCreate
07-15 03:16:46.998: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:16:52.980: I/MyIntentService(3186): onHandleIntent end
07-15 03:16:52.980: I/MyIntentService(3186): onHandleIntent thread:Thread[IntentService[MyIntentService],5,main]
07-15 03:17:01.048: I/MyIntentService(3186): onHandleIntent end
07-15 03:17:01.053: I/MyIntentService(3186): onDestroy

正常startService啟動兩個任務,第一個未完成前,將第二個任務放到隊列中,等待第一個完成后執行第二個任務,第二個任務完成后,Service自動銷毀。

5 點擊“啟動任務一”,任務完成前點擊“停止Service”,然后再點擊“啟動任務二”。

啟動 停止 啟動

log信息

第一個任務尚未結束時stopservice,IntentService銷毀,其線程繼續運行(tid 3691)。此時重新startService會開啟IntentService,其會重新創建一個線程運行任務(tid 3692)。兩個任務在兩個線程中運行,所以其執行完的先后順序不確定。


3 IntentService源碼解析

路徑:frameworks/base/core/java/android/app/IntentService.java
先看下IntentService的構造方法和onCreate()。

public abstract class IntentService extends Service {
    //Creates an IntentService.  Invoked by your subclass's constructor.
    public IntentService(String name) {
        super();
            mName = name;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }
    。。。。
}

IntentService 是繼承Service的一個抽象類,所以需要繼承IntentService 并必須實現其抽象方法onHandleIntent。
繼承IntentService需要實現一個空的構造器,并且調用IntentService的構造器。
在onCreate()方法中創建了一個HandlerThread,并允許該線程。HandlerThread 不太懂的可以參考我的上一篇文章Android HandlerThread詳解
獲取子線程中的Looper實例,然后創建與子線程綁定的Handler對象。

接著看IntentService的onStart()。

public void onStart(Intent intent, int startId) {
    Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
}

在onStart方法中,創建Message對象,并將“消息”通過mServiceHandler發送到子線程中的消息隊列中。
我們知道這些消息處理還是會分發到Handler中。接著看mServiceHandler

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);
        }
}

消息會在handlerMessage中處理,該方法中調用了onHandleIntent,所以我們需要實現onHandleIntent,在該方法中做我們要做的任務。而消息處理完成后,調用stopSelf將自身Service銷毀。這里可能會有疑問,既然一個任務執行完成后就會執行stopSelf,那多個任務是怎么處理的呢?這里stopSelf(msg.arg1),會先看隊列中是否有消息待處理,如果有則繼續處理后面的消息,沒有才會將Service銷毀。
接著看IntentService的onDestroy方法

@Override
public void onDestroy() {
    mServiceLooper.quit();
}

在IntentService的onDestroy方法中會調用looper的quit方法,將子線程的消息循環停止,等待任務完成后結束子線程。


4 總結

IntentService是一個比較便捷的類,省了我們在創建Thread,但是并不能適合所有的情況,它會創建一個線程,多個任務按順序執行,并且執行過程中不能夠取消該任務。所以還是需要根據情況進行使用。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,885評論 6 541
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,312評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,993評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,667評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,410評論 6 411
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,778評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,775評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,955評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,521評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,266評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,468評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,998評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,696評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,095評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,385評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,193評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,431評論 2 378

推薦閱讀更多精彩內容