對IntentService的理解

閱讀此文前請先閱讀對HandlerThread的理解,有助于理解IntentService。

概述

IntentService繼承了Service并且是一個抽象類,使用它必須創(chuàng)建它的子類。IntentService可執(zhí)行后臺耗時的任務,當任務結束時它會自動停止。由于IntentService是一種服務,所以它的優(yōu)先級會比普通線程的高,適合執(zhí)行一些高優(yōu)先級的后臺任務,因為高優(yōu)先級不容易被系統(tǒng)殺死。

工作原理

IntentService封裝了HandlerThread和Handler,在onCreate方法中創(chuàng)建HandlerThread和Handler,并把handler和HandlerThread的Looper關聯起來

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

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

每一次啟動IntentService,onStartCommand方法會被調用,處理每個后臺任務的Intent.

    public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

上面代碼可以知道,onStartCommand又調用了onStart(intent, startId)

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

onStart方法通過mServiceHandler把Intent對象發(fā)送出去,這個Intent對象跟外界的startService(intent)中的intent是一致的

我們看看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);
        }
    }

handleMessage方法調用了onHandleIntent((Intent)msg.obj)。onHandleIntent是個抽象方法,我們需要在IntentService的子類重寫它,所以在這里我們可以進行耗時任務的執(zhí)行。通過不同的intent參數,我們就可以進行不同的后臺任務處理了。onHandleIntent方法執(zhí)行完畢后調用stopSelf(int startId)自動停止任務,之所以調用stopSelf(int startId)而不是stopSelf(),是因為stopSelf()會馬上停止任務,但這時可能會有其他任務還沒處理,stopSelf(int startId)會等待所有任務處理之后再停止任務。
由于IntentService內部是通過handler的形式發(fā)送消息處理任務的,Looepr是按順序處理消息的,所以IntentService也是按啟動順序執(zhí)行后臺任務。

通過以上的分析,我們知道IntentService的使用重點在于重寫onHandleIntent方法,對不同的intent對象進行不同的處理,啟動IntentService時對intent傳入參數,通過這些參數作為標識就可以進行不同任務的處理

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容