Android IntentService的使用和源碼分析

引言

Service服務是Android四大組件之一,在Android中有着舉足重輕的做用。Service服務是工做的UI線程中,當你的應用須要下載一個文件或者播放音樂等長期處於後臺工做而有沒有UI界面的時候,你確定要用到Service+Thread來實現。所以你須要本身在Service服務裏面實現一個Thread工做線程來下載文件或者播放音樂。然而你每次都須要本身去寫一個Service+Thread來處理長期處於後臺而沒有UI界面的任務,這樣顯得很麻煩,不必每次都去構建一個Service+Thread框架處理長期處於後臺的任務。Google工程師給咱們構建了一個方便開發者使用的這麼一個框架---IntentService。html

IntentService簡介

IntentService是一個基礎類,用於處理Intent類型的異步任務請求。當客戶端調用android.content.Context#startService(Intent)發送請求時,Service服務被啓動,且在其內部構建一個工做線程來處理Intent請求。當工做線程執行結束,Service服務會自動中止。IntentService是一個抽象類,用戶必須實現一個子類去繼承它,且必須實現IntentService裏面的抽象方法onHandleIntent來處理異步任務請求。android

IntentServic示例

Client代碼

public class ClientActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    //客戶端同時發送兩個任務到IntentService服務端執行
    public void send(View view) {
        Intent intent = new Intent(this, DownLoadService.class);
        intent.putExtra("key", 1);
        intent.putExtra("value", "the first task1");
        startService(intent);

        Intent intent1 = new Intent(this, DownLoadService.class);
        intent1.putExtra("key", 2);
        intent1.putExtra("value", "the second task2");
        startService(intent1);
    }
}

模擬兩個異步任務同時請求,經過Intent實例攜帶數據啓動Service服務。瀏覽器

Service客戶端

public class DownLoadService extends IntentService {

    public static final String TAG = "DownLoadService";
    //重寫默認的構造方法
    public DownLoadService() {
        super("DownLoadService");
    }

    //在後臺線程執行
    @Override
    protected void onHandleIntent(Intent intent) {
        int key = intent.getIntExtra("key", 0);
        String value = intent.getStringExtra("value");
        switch (key) {
            case 1:
                //模擬耗時任務1
                try {
                    Thread.sleep(3 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                break;
            case 2:
                //模擬耗時任務1
                try {
                    Thread.sleep(3 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }

        Log.e(TAG, "\nthe current time is: " + System.currentTimeMillis()/1000
                + "\nthe Thread id is " + Thread.currentThread().getId()
                + "\nthe current task is " + value);
    }
}

DownLoadService子類繼承IntentService類,而後實現onHandleIntent抽象方法進行處理Intent請求的異步任務。在服務端DownLoadService類中,咱們並無建立Thread線程去執行異步耗時任務請求。全部的異步耗時任務都是在onHandleIntent抽象方法中實現了。言外之意是IntentService類內部已經幫開發者搭建好了一個異步任務處理器,用戶只需實現其中的onHandleIntent抽象方法去處理異步任務便可,從而讓開發者更加簡單方便的使用IntentService處理後臺異步任務請求。那麼IntentService內部是怎麼搭建異步任務處理器的呢?咱們不妨查看源碼來窺探個究竟。微信

IntentService源碼分析

IntentService構造方法

/**
     * 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;
    }

分析:該構造方法需在子類中調用,用於建立一個IntentService對象。參數name用於定義工做線程的名稱,僅僅用於調式做用。咱們知道Service服務的生命週期是從onCreate方法開始的。那麼就來看看IntentService#onCreate方法吧。app

IntentService#onCreate方法

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類建立了一個循環的工做線程thread,而後將工做線程中的Looper對象做爲參數來建立ServiceHandler消息執行者。由另外一篇博客Android HandlerThread 源碼分析可知,HandlerThread+Handler構建成了一個帶有消息循環機制的異步任務處理機制。所以開發者就能夠將異步任務封裝成消息的形式發送到工做線程中去執行了。Service服務生命週期第二步執行IntentService#onStartCommand方法。框架

IntentService#onStartCommand方法

/**
     * 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
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

分析:在IntentService子類中你無需重寫該方法。而後你須要重寫onHandlerIntent方法,系統會在IntentService接受一個請求開始調用該方法。咱們看到在該方法中僅僅是調用了onStart方法而已,跟蹤代碼:異步

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

分析:該方法中經過mServiceHandler得到一個消息對象msg,而後將startId做爲該消息的消息碼,將異步任務請求intent做爲消息內容封裝成一個消息msg發送到mServiceHandler消息執行者中去處理,那麼咱們來看看mServiceHandler的實現吧!ide

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是IntentService的內部類,在重寫消息處理方法handlerMessage裏面調用了onHandlerIntent抽象方法去處理異步任務intent的請求,當異步任務請求結束以後,調用stopSelf方法自動結束IntentService服務。看過博客Android HandlerThread 源碼分析的人都應該知道,此處handleMessage方法是在工做線程中調用的,所以咱們子類重寫的onHandlerIntent也是在工做線程中實現的。咱們來看看onHandlerIntent方法:oop

/**
     * 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)}.
     */
    protected abstract void onHandleIntent(Intent intent);

分析:該方法用於處理intent異步任務請求,在工做線程中調用該方法。每個時刻只能處理一個intent請求,當同時又多個intent請求時,也就是客戶端同時屢次調用Content#startService方法啓動同一個服務時,其餘的intent請求會暫時被掛起,直到前面的intent異步任務請求處理完成纔會處理下一個intent請求。直到全部的intent請求結束以後,IntentService服務會調用stopSelf中止當前服務。也就是當intent異步任務處理結束以後,對應的IntentService服務會自動銷燬,進而調用IntentService#onDestroy方法:源碼分析

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

該方法中調用HandlerThread工做線程中Looper對象的quit方法讓當前工做線程HandlerThread退出當前Looper循環,進而結束線程。進而結束當前IntentService服務。到此,整個IntentService服務結束,如今能夠用一張流程圖來描述整個過程以下:

這裏寫圖片描述

IntentService總結

  1. 子類需繼承IntentService而且實現裏面的onHandlerIntent抽象方法來處理intent類型的任務請求。
  2. 子類須要重寫默認的構造方法,且在構造方法中調用父類帶參數的構造方法。
  3. IntentService類內部利用HandlerThread+Handler構建了一個帶有消息循環處理機制的後臺工做線程,客戶端只需調用Content#startService(Intent)將Intent任務請求放入後臺工做隊列中,且客戶端無需關注服務是否結束,很是適合一次性的後臺任務。好比瀏覽器下載文件,退出當前瀏覽器以後,下載任務依然存在後臺,直到下載文件結束,服務自動銷燬。
  4. 只要當前IntentService服務沒有被銷燬,客戶端就能夠同時投放多個Intent異步任務請求,IntentService服務端這邊是順序執行當先後臺工做隊列中的Intent請求的,也就是每一時刻只能執行一個Intent請求,直到該Intent處理結束才處理下一個Intent。由於IntentService類內部利用HandlerThread+Handler構建的是一個單線程來處理異步任務。

【轉載請註明出處:http://www.cnblogs.com/feidu/p/8074268.html 廢墟的樹】 掃碼關注微信公衆號「Android知識傳播」,不定時傳播經常使用Android基礎知識。

相關文章
相關標籤/搜索