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

前言

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

相關文章閱讀
AsyncTask
HandlerThread


1 使用步驟

  • ①創建IntentService子類(因為IntentService是抽象類)
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中注冊
  <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>
  • ③啟動
   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的生命周期,我們可直接通過分析生命周期來了解其運行的原理。
一、從onCreate方法可以看出IntentService內部封裝了HandlerThread和Handler,從這里可以看出IntentService可以用于執行后臺任務

    @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調用了onStart,并通過mServiceHandler發送消息。

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

三、調用onHandleIntent方法,最后調用stopSelf停止服務。

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

總結

  • IntentService是一種特殊的Service,但是不能支持bindservice。
  • 因為IntentService是服務使得它的優先級較高,所以可以用IntentService執行一些高優先級的后臺任務。
  • 優先級較高因此不容易被kill。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容