IntentService淺析

IntentService淺析

說起IntentService就需要先了解一下Service

Service 是長期運行在後臺的應用程序組件。

Service 不是一個單獨的進程,它和應用程序在同一個進程中,Service 也不是一個線程,它和線程沒有任何關係,所以它不能直接處理耗時操作。如果直接把耗時操作放在 Service 的 onStartCommand() 中,很容易引起 ANR(ActivityManagerService.java中定義了超時時間,前臺service超過20S,後臺Service超過200S無響應就會ANR) 。如果有耗時操作就必須開啓一個單獨的線程來處理。

既然Service不能直接執行耗時操作,那麼在Service開啓子線程執行耗時操作不就好了。當然,這麼想完全沒毛病,在Service中執行耗時操作也只能這麼幹。如:

public int onStartCommand(Intent intent, int flags, int startId) {
    
    Thread thread = new Thread(){
        @Override
        public void run() {
            
            /**
             * 耗時的代碼在子線程裏面寫
             */
            
        }
    };
    thread.start();
    
    return super.onStartCommand(intent, flags, startId);
}

正如前面說到,Service是長期運行在後臺的應用程序組件,那麼Service一旦啓動就會一直運行下去,必須人爲調用stopService()或者stopSelf()方法才能讓服務停止下來。如果耗時操作只想執行一次,那麼必須在執行耗時操作的子線程執行完後就結束Service自身。如:

public void run() {
            
 	/**
 	 * 耗時的代碼在子線程裏面寫
 	*/
	stopSelf();
}

或者在代碼裏的某個地方調用stopService()或者stopSelf()方法。

這麼做是否很麻煩呢?如果忘記在Service開始子線程呢?如果忘記結束Service呢?

所以引入了今天的話題:IntentService

IntentService 是繼承於 Service 並處理異步請求的一個類,在 IntentService 內有一個工作線程來處理耗時操作,啓動 IntentService 的方式和啓動傳統 Service 一樣,同時,當任務執行完後,IntentService 會自動停止,而不需要我們去手動控制。另外,可以啓動 IntentService 多次,而每一個耗時操作會以工作隊列的方式在IntentService 的 onHandleIntent 回調方法中執行,並且,每次只會執行一個工作線程,執行完第一個再執行第二個,以此類推。

而且,所有請求都在一個單線程中,不會阻塞應用程序的主線程(UI Thread),同一時間只處理一個請求。 那麼,用 IntentService 有什麼好處呢?首先,我們省去了在 Service 中手動開線程的麻煩,第二,當操作完成時,我們不用手動停止 Service。

IntentService源碼分析

package android.app;

import android.annotation.WorkerThread;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;

/**
 * IntentService is a base class for {@link Service}s that handle asynchronous
 * requests (expressed as {@link Intent}s) on demand.  Clients send requests
 * through {@link android.content.Context#startService(Intent)} calls; the
 * service is started as needed, handles each Intent in turn using a worker
 * thread, and stops itself when it runs out of work.
 *
 * <p>This "work queue processor" pattern is commonly used to offload tasks
 * from an application's main thread.  The IntentService class exists to
 * simplify this pattern and take care of the mechanics.  To use it, extend
 * IntentService and implement {@link #onHandleIntent(Intent)}.  IntentService
 * will receive the Intents, launch a worker thread, and stop the service as
 * appropriate.
 *
 * <p>All requests are handled on a single worker thread -- they may take as
 * long as necessary (and will not block the application's main loop), but
 * only one request will be processed at a time.
 *
 * <div class="special reference">
 * <h3>Developer Guides</h3>
 * <p>For a detailed discussion about how to create services, read the
 * <a href="{@docRoot}guide/topics/fundamentals/services.html">Services</a> developer guide.</p>
 * </div>
 *
 * @see android.os.AsyncTask
 */
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(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(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
    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)}.
     */
    @WorkerThread
    protected abstract void onHandleIntent(Intent intent);
}

Service有startService()bindService()兩種啓動方式,那麼IntentService是否也有呢?

 	/**
     * 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
    public IBinder onBind(Intent intent) {
        return null;
    }

IntentService 源碼中的 onBind() 默認返回 null;不適合 bindService() 啓動服務,如果你執意要 bindService() 來啓動 IntentService,可能因爲你想通過 Binder 或 Messenger 使得 IntentService 和 Activity 可以通信,這樣那麼 onHandleIntent() 不會被回調,相當於在你使用 Service 而不是 IntentService。因此,並不建議通過 bindService() 啓動 IntentService,而是通過startService()來啓動IntentService。

爲什麼多次啓動 IntentService 會順序執行事件,停止服務後,後續的事件得不到執行?

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

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

IntentService 中使用的 Handler、Looper、MessageQueue 機制把消息發送到線程中去執行的,所以多次啓動 IntentService 不會重新創建新的服務和新的線程,只是把消息加入消息隊列中等待執行,而如果服務停止,會清除消息隊列中的消息,後續的事件得不到執行。

使用方法:

1、創建一個類並繼承IntentService,重寫onHandleIntent(),構造函數super("線程名");

2、在AndroidManifest.xml裏註冊,同Service;

3、通過startService()啓動。

package com.eebbk.synchinese.widgetutil;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;

/**
 * 刷新桌面掛件
 * Created by zhangshao on 2018/2/28.
 */
public class WidgetUpdateService extends IntentService {

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

	@Override
	protected void onHandleIntent(@Nullable Intent intent) {
		synchronized (this) {
			FastOpenBookUtil.refreshLearnBookWidgetBroadCast(this);
		}
	}
}

附:

ActivityManagerService.java中ANR的超時時間定義:

1、Broadcast超時時間爲10秒:

// How long we allow a receiver to run before giving up on it.
static final int BROADCAST_FG_TIMEOUT = 10*1000;
static final int BROADCAST_BG_TIMEOUT = 60*1000;

2、按鍵無響應的超時時間爲5秒

// How long we wait until we timeout on key dispatching.
static final int KEY_DISPATCHING_TIMEOUT = 5*1000;

3、Service的ANR在ActiveServices中定義:

前臺service無響應的超時時間爲20秒,後臺service爲200秒

// How long we wait for a service to finish executing.
static final int SERVICE_TIMEOUT = 20*1000;

// How long we wait for a service to finish executing.
static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章