Android多線程:如何正確使用IntentService?

前言

?Android沿用了Java的線程模型,除了Thread外,Android還實(shí)現(xiàn)了AsyncTask、HandlerThread、IntentService,它們的底層實(shí)現(xiàn)也是線程。
?本文講的是IntentService

相關(guān)文章閱讀
AsyncTask
HandlerThread


1 使用步驟

  • ①創(chuàng)建IntentService子類(因?yàn)镮ntentService是抽象類)
class WorkerIntentService(name: String?) : IntentService(name) {
    var tag = "WorkerIntentService"
    override fun onHandleIntent(intent: Intent?) {
        val action = intent?.getStringExtra("shopping")
        Log.d(tag,"onHandleIntent:${action}")
        SystemClock.sleep(250)
    }

    override fun onCreate() {
        Log.d(tag,"onCreate")
        super.onCreate()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(tag,"onStartCommand")
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        Log.d(tag,"onDestroy")
        super.onDestroy()
    }

}
  • ②AndroidManifest.xml中注冊(cè)
  <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".WorkerIntentService" />
    </application>
  • ③啟動(dòng)
   private fun myService() {
        val intent = Intent(this,WorkerIntentService::class.java)
        val bundle = Bundle()
        bundle.putString("shopping", "go go go")
        intent.putExtras(bundle)
        startService(intent)
        val fireIntent = Intent(this,WorkerIntentService::class.java)
        val fireBundle = Bundle()
        fireBundle.putString("shopping", "fire fire fire")
        fireIntent.putExtras(fireBundle)
        startService(fireIntent)
        startService(intent)
    }

2 源碼分析

IntentService是Service,因此也遵循Service的生命周期,我們可直接通過(guò)分析生命周期來(lái)了解其運(yùn)行的原理。
一、從onCreate方法可以看出IntentService內(nèi)部封裝了HandlerThread和Handler,從這里可以看出IntentService可以用于執(zhí)行后臺(tái)任務(wù)

    @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);
    }

二、onStartCommand調(diào)用了onStart,并通過(guò)mServiceHandler發(fā)送消息。

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

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

三、調(diào)用onHandleIntent方法,最后調(diào)用stopSelf停止服務(wù)。

 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);
        }
    }

四、onBind返回的是null,因此IntentService不支持bindservice

    @Override
    @Nullable
    public IBinder onBind(Intent intent) {
        return null;
    }

總結(jié)

  • IntentService是一種特殊的Service,但是不能支持bindservice。
  • 因?yàn)镮ntentService是服務(wù)使得它的優(yōu)先級(jí)較高,所以可以用IntentService執(zhí)行一些高優(yōu)先級(jí)的后臺(tái)任務(wù)。
  • 優(yōu)先級(jí)較高因此不容易被kill。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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