IntentService 詳解(從使用到源碼擼一遍)

為什么會(huì)有IntentService?

我們知道,Service作為四大組件之一,也會(huì)是運(yùn)行在主線程的,所以我們?nèi)绻泻臅r(shí)的操作,應(yīng)該新開(kāi)一個(gè)線程。
為此android專門提供了一個(gè)類,就是IntentService,它的里邊包含了一個(gè)handler用于處理后臺(tái)線程。
使用IntentService,首先繼承它,然后實(shí)現(xiàn)onHandleIntent()方法。

舉個(gè)例子,模擬上傳和下載文件的demo:
我的IntentService:

package example.ylh.com.service_demo;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

/**
 * Created by yangLiHai on 2017/8/30.
 */

public class TestIntentService extends IntentService {

    private String TAG = TestIntentService.class.getSimpleName();
    public static final String ACTION_UPLOAD_FILE = "action_upload_file";
    public static final String ACTION_DOWNLOAD_FILE = "action_download_file";

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     *  Used to name the worker thread, important only for debugging.
     */
    public TestIntentService() {
        super("test intent service");
        Log.e(TAG,"construction");
    }

    @Override
    public void onCreate() {
        Log.e(TAG,"oncreate");
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        Log.e(TAG,"ondestroy");
        super.onDestroy();
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        String action = intent.getAction();
        if (action.equals(ACTION_DOWNLOAD_FILE)){
            downloadFile();
        }else if (action.equals(ACTION_UPLOAD_FILE)){
            uploadFile();
        }
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void uploadFile(){

        Log.e(TAG,"handleintent upload:"+Thread.currentThread().getId()+"");
    }
    private void downloadFile(){

        Log.e(TAG,"handleintent download:"+Thread.currentThread().getId()+"");
    }
}

activity代碼:

package example.ylh.com.service_demo;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

import example.ylh.com.R;

/**
 * Created by yanglihai on 2017/8/17.
 */

public class ServiceTestActivity extends Activity {

    public static final String TAG = ServiceTestActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.service_test_activity);

        findViewById(R.id.btn4).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startUploadService();
            }
        });
        findViewById(R.id.btn5).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startDownloadService();
            }
        });
    }

    public void startDownloadService(){
        Intent i = new Intent(ServiceTestActivity.this, TestIntentService.class);
        i.setAction(TestIntentService.ACTION_DOWNLOAD_FILE);
        startService(i);
    }
    public void startUploadService(){
        Intent i = new Intent(ServiceTestActivity.this, TestIntentService.class);
        i.setAction(TestIntentService.ACTION_UPLOAD_FILE);
        startService(i);
    }


}

通過(guò)Intent來(lái)傳遞數(shù)據(jù),分發(fā)不同的任務(wù)。多次調(diào)用會(huì)被內(nèi)部的handler放到隊(duì)列中,任意時(shí)間只有一個(gè)intent正在被處理,隊(duì)列中沒(méi)有需要處理的任務(wù)的時(shí)候,就會(huì)銷毀自己。
多次點(diǎn)擊兩個(gè)按鈕的打印結(jié)果如下:

可以清楚地看到,上傳和下載任務(wù)都是在子線程中執(zhí)行的,當(dāng)所有的任務(wù)執(zhí)行完之后就會(huì)destroy。所以使用IntentService我們不用考慮Service的生命周期,也不用自己創(chuàng)建子線程開(kāi)啟任務(wù),一切都幫我們做好了,用起來(lái)還是很方便的。

IntentService源碼解析

IntentService繼承自Service,他是一個(gè)特殊的service,它的內(nèi)部封裝了HandlerThread和Handler。
這是它的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);
    }

第一次啟動(dòng)的時(shí)候,onCreate方法會(huì)被調(diào)用,創(chuàng)建了一個(gè)HandlerThread,然后使用它的looper來(lái)構(gòu)造mServiceHandler(一個(gè)handler對(duì)象)。這樣mServiceHandler就可以在子線程處理任務(wù)了。執(zhí)行完oncreat之后,就會(huì)執(zhí)行onStartCommand方法,多次啟動(dòng)IntentService就會(huì)多次調(diào)用onStartCommand方法,
這是onStartCommand方法的具體代碼:

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

可以看見(jiàn)里邊調(diào)用了onStart方法,我們?cè)賮?lái)看看onStart方法:

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

在onStart方法中,每次都會(huì)用mServiceHandler發(fā)送一個(gè)消息,然后我們?cè)诳纯磎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);
      }
  }

可以清楚地看到,每次收到intent之后,都會(huì)把intent交給onHandleIntent方法去處理,也就是我們需要重寫的方法,通過(guò)intent我們可以解析出來(lái)外界傳進(jìn)來(lái)的數(shù)據(jù),做相應(yīng)的處理。onHandleIntent執(zhí)行完之后,又執(zhí)行了stopSelf(int startid)方法去關(guān)閉自身。但是他不是立刻去關(guān)閉,而是等待所有的intent被處理完之后才終止服務(wù)。一般來(lái)說(shuō),stopSelf(int startId)在關(guān)閉之前都會(huì)判斷最近啟動(dòng)服務(wù)的次數(shù)和startId是否相等,如果相等就立刻停止服務(wù),如果不相等,則不停止。

IntentService多數(shù)情況下都非常簡(jiǎn)單實(shí)用,你只需要生成后臺(tái)任務(wù)操作,而不用關(guān)系啟動(dòng)時(shí)機(jī),如果給IntentService發(fā)送多個(gè)Intent,這些Intent會(huì)按順序執(zhí)行,每次執(zhí)行一個(gè)。如果有并發(fā)需求,并不適合用IntentService,還是自己寫Service吧。

IntentService到這里已經(jīng)說(shuō)完了,看完我的例子在看看源碼,相信你已經(jīng)能完全理解了。
如果那里說(shuō)的不夠準(zhǔn)確請(qǐng)給我留言,謝謝。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容