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

來源:互聯網
上載者:User

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自身;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.