IntentService源碼分析

1 概論

IntentService是一種處理異步請求的Service。客戶端通過調(diào)用Context.startService(Intent)來發(fā)送請求,啟動Service;Service按需啟動后,會依次按順序處理工作線程中的Intent,并且在工作結(jié)束后會自動停止。

2 IntentService是如何啟動一個(gè)異步線程處理請求的?

IntentService在創(chuàng)建時(shí),會創(chuàng)建并啟動一個(gè)線程HandlerThread,并且賦予這個(gè)線程一個(gè)Looper;

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

ServiceHandler是Handler的一個(gè)子類,用來接受處理消息Message,我們知道一般Handler是在UI主線程接受處理消息的,要想在異步線程接受處理消息,必須給這個(gè)異步線程關(guān)聯(lián)一個(gè)Looper,并且在異步線程調(diào)用Looper.prepare()方法;

public class HandlerThread extends Thread {
    int mPriority;
    int mTid = -1;
    Looper mLooper;
    
    public HandlerThread(String name) {
        super(name);
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }
    ...
    @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }
    ...
}

3 IntentService是如何處理Intent的

調(diào)用Context.startService(Intent)后,Service被啟動,執(zhí)行onCreate()方法,然后執(zhí)行onStart(Intent intent,int startId);

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

可以看到Service開始后,會把Intent對象通過Handler機(jī)制交給ServiceHandler來處理,ServiceHandler接受到消息后:

    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接受到消息后,取出Intent,啟動onHandleIntent(Intent) 方法,來處理Intent;

我們來看onHandleIntent(Intent intent);

protected abstract void onHandleIntent(Intent intent);

這是一個(gè)抽象方法,留給開發(fā)者自己實(shí)現(xiàn),異步操作的實(shí)現(xiàn)邏輯都在這個(gè)抽象方法里面;操作完成后,通過調(diào)用stopSelf() Service

4 總結(jié)

  1. IntentService在創(chuàng)建的時(shí)候會創(chuàng)建一個(gè)線程,并啟動這個(gè)異步線程;
  2. 創(chuàng)建的異步線程會利用Looper、Handler來創(chuàng)建、發(fā)送、接受消息Message,與UI主線程通過Handler機(jī)制進(jìn)行線程通信是同理的;
  3. Service的異步操作邏輯是定義在抽象方法onHandleIntent(Intent)里面,開發(fā)者需要實(shí)現(xiàn)這個(gè)抽象方法;
  4. ServiceHandler處理消息是在異步線程里面的,onHandleIntent(Intent)也是運(yùn)行在異步線程里面的,這與UI主線程里面的Handler不同;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容