Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> android源碼解析之(四)--)IntentService

android源碼解析之(四)--)IntentService

編輯:關於android開發

android源碼解析之(四)--)IntentService


什麼是IntentService?簡單來說IntentService就是一個含有自身消息循環的Service,首先它是一個service,所以service相關具有的特性他都有,同時他還有一些自身的屬性,其內部封裝了一個消息隊列和一個HandlerThread,在其具體的抽象方法:onHandleIntent方法是運行在其消息隊列線程中,廢話不多說,我們來看其簡單的使用方法:

定義一個IntentService
public class MIntentService extends IntentService{

    public MIntentService() {
        super("");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.i("tag", intent.getStringExtra("params") + "  " + Thread.currentThread().getId());
    }

}
在androidManifest.xml中定義service
啟動這個service
title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MIntentService.class);
                intent.putExtra("params", "ceshi");
                startService(intent);
            }
        });

可以發現當點擊title組件的時候,service接收到了消息並打印出了傳遞過去的intent參數,同時顯示onHandlerIntent方法執行的線程ID並非主線程,這是為什麼呢?

下面我們來看一下service的源碼:

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.
     *
     * 

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. * *

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

怎麼樣,代碼還是相當的簡潔的,首先通過定義我們可以知道IntentService是一個Service,並且是一個抽象類,所以我們在繼承IntentService的時候需要實現其抽象方法:onHandlerIntent。

下面看一下其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);
    }

我們可以發現其內部定義一個HandlerIThread(本質上是一個含有消息隊列的線程)
然後用成員變量維護其Looper和Handler,由於其Handler關聯著這個HandlerThread的Looper對象,所以Handler的handMessage方法在HandlerThread線程中執行。

然後我們發現其onStartCommand方法就是調用的其onStart方法,具體看一下其onStart方法:

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

很簡單就是就是講startId和啟動時接受到的intent對象傳遞到消息隊列中處理,那麼我們具體看一下其消息隊列的處理邏輯:

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方法內部執行了兩個邏輯一個是調用了其onHandlerIntent抽象方法,通過分析其onCreate方法handler對象的創建過程我們知道其handler對象是依附於HandlerThread線程的,所以其handeMessage方法也是在HandlerThread線程中執行的,從而證實了我們剛剛例子中的一個結論,onHandlerIntent在子線程中執行。
然後調用了stopSelf方法,這裡需要注意的是stopSelf方法傳遞了msg.arg1參數,從剛剛的onStart方法我們可以知道我們傳遞了startId,參考其他文章我們知道,由於service可以啟動N次,可以傳遞N次消息,當IntentService的消息隊列中含有消息時調用stopSelf(startId)並不會立即stop自己,只有當消息隊列中最後一個消息被執行完成時才會真正的stop自身。

通過上面的例子與相關說明,我們可以知道:

IntentService是一個service,也是一個抽象類;

繼承IntentService需要實現其onHandlerIntent抽象方法;

onHandlerIntent在子線程中執行;

IntentService內部保存著一個HandlerThread、Looper與Handler等成員變量,維護這自身的消息隊列;

每次IntentService後台任務執行完成之後都會嘗試關閉自身,但是當且僅當IntentService消息隊列中最後一個消息被執行完成之後才會真正的stop自身;

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved