IntentService 使用與原理

IntentService

簡介

  • 在Service裏面不能直接進行耗時操作,一般都需要去開啓子線程,如果自己去管理Service的生命週期以及子線程難免會不完善,Android提供了一個類,IntentService。
  • IntentService是一個基於Service的一個類,用來處理異步的請求。你可以通過startService(Intent)來提交請求,該Service會在需要的時候創建,當完成所有的任務以後自己關閉,而不需要我們去手動控制

使用

需要繼承IntentService,然後複寫onHandleIntent方法

public class UploadImgService extends IntentService {

    private static final String ACTION_UPLOAD_IMG = "com.jsj.handlerthreaddemo.action.UPLOAD_IMAGE";
    public static final String EXTRA_IMG_PATH = "com.jsj.handlerthreaddemo.extra.IMG_PATH";


    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     *             給線程設置名字
     */
    public UploadImgService(String name) {
        super(name);
    }

    public UploadImgService() {
        super("UploadImgService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_UPLOAD_IMG.equals(action)) {
                final String path = intent.getStringExtra(EXTRA_IMG_PATH);//獲取要處理的數據
                //TODO 處理數據,然後通過廣播將數據發送出去
                Intent intent = new Intent(IntentServiceActivity.UPLOAD_RESULT);
                intent.putExtra(EXTRA_IMG_PATH, path);
                sendBroadcast(intent);//將處理完的數據通過廣播的形式發送出去
            }
        }
    }

開啓服務

//開啓服務,並將需要處理的數據傳遞過去
Intent intent = new Intent(context, UploadImgService.class);
        intent.setAction(ACTION_UPLOAD_IMG);
        intent.putExtra(EXTRA_IMG_PATH, path);
        context.startService(intent);

通過廣播接受者來接收發送過來的數據

private BroadcastReceiver uploadImgReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() == UPLOAD_RESULT) {
                String path = intent.getStringExtra(UploadImgService.EXTRA_IMG_PATH);
                tv.setText(path + " upload success ~~~ ");
            }
        }
    };

源碼

不多就都貼了出來,容易看

public abstract class IntentService extends Service {
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;
    private String mName;
    private boolean mRedelivery;

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

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public IntentService(String name) {
        super();
        mName = name;
    }

    /**
     * Sets intent redelivery preferences.  Usually called from the constructor
     * with your preferred semantics.
     *
     * <p>If enabled is true,
     * {@link #onStartCommand(Intent, int, int)} will return
     * {@link Service#START_REDELIVER_INTENT}, so if this process dies before
     * {@link #onHandleIntent(Intent)} returns, the process will be restarted
     * and the intent redelivered.  If multiple Intents have been sent, only
     * the most recent one is guaranteed to be redelivered.
     *
     * <p>If enabled is false (the default),
     * {@link #onStartCommand(Intent, int, int)} will return
     * {@link Service#START_NOT_STICKY}, and if the process dies, the Intent
     * dies along with it.
     */
    public void setIntentRedelivery(boolean enabled) {
        mRedelivery = enabled;
    }

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

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

    /**
     * You should not override this method for your IntentService. Instead,
     * override {@link #onHandleIntent}, which the system calls when the IntentService
     * receives a start request.
     * @see android.app.Service#onStartCommand
     */
    @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 onDestroy() {
        mServiceLooper.quit();
    }

    /**
     * Unless you provide binding for your service, you don't need to implement this
     * method, because the default implementation returns null.
     * @see android.app.Service#onBind
     */
    @Override
    @Nullable
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * This method is invoked on the worker thread with a request to process.
     * Only one Intent is processed at a time, but the processing happens on a
     * worker thread that runs independently from other application logic.
     * So, if this code takes a long time, it will hold up other requests to
     * the same IntentService, but it will not hold up anything else.
     * When all requests have been handled, the IntentService stops itself,
     * so you should not call {@link #stopSelf}.
     *
     * @param intent The value passed to {@link
     *               android.content.Context#startService(Intent)}.
     *               This may be null if the service is being restarted after
     *               its process has gone away; see
     *               {@link android.app.Service#onStartCommand}
     *               for details.
     */
    @WorkerThread
    protected abstract void onHandleIntent(@Nullable Intent intent);

分析

1.onCreate裏面初始化了一個HandlerThread
@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);
    }
2.每次調用onStartCommand的時候,通過mServiceHandler發送一條帶startId和Intent的消息,然後在該mServiceHandler的handleMessage中去回調onHandleIntent(intent);
@Override
    public void onStart(@Nullable Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }
當回調onHandleIntent(intent)後調用了方法stopSelf(msg.arg1);
 @Override
        public void handleMessage(Message msg) {
            onHandleIntent((Intent)msg.obj);
            stopSelf(msg.arg1);
        }

跟下stopSelf方法,傳入了一個int類型,當前發送的標識是最近發出的那一個

當所有的工作執行完後:就會執行onDestroy方法,然後調用方法 mServiceLooper.quit()使looper停下來.

@Override
    public void onDestroy() {
        mServiceLooper.quit();
    }

總結:

  • IntentService是繼承於Service並處理異步請求的一個類

  • 當完成所有的任務以後自己關閉,而不需要我們去手動控制

  • 可以啓動多次,每啓動一次,就會新建一個work thread,但IntentService的實例始終只有一個,onCreate方法只執行了一次,而onStartCommand和onStart方法執行多次

  • 在IntentService內擁有一個HandlerThread,獲得工作線程的 Looper,並維護自己的工作隊列

  • 可以啓動IntentService多次,而每一個耗時操作會以工作隊列的方式在IntentService的onHandleIntent回調方法中執行,並且,每次只會執行一個工作線程,執行完第一個再執行第二個,按順序執行

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章