IntentService相关问题总结

IntentService是什么

IntentService是继承自Service并处理异步请求的一个类,但是优先级比Service高;
在IntentService内有一个工作线程来处理耗时操作(通过HandlerThread和Handler实现);
启动IntentService方式和传统Service一样;
区别在于执行完任务后,IntentService会自动停止,而不需要我们手动去控制或stopSelf();
另外,可以启动IntentService多次,而每一个耗时操作会以工作队列的方式在IntentService的onHandleIntent回调方法中执行,并且每次只会执行一个工作线程,执行完第一个再执行第二个;

IntentService 的使用方法

image

  1. IntentService 是一个抽象类, 需要具体实现, 首先实现一个 MyIntentService;

  2. 必须实现两个方法, 一个是构造方法, 一个是 onHandleIntent 方法;
    构造方法里传入一个字符串表示服务名称。
    onHandleIntent里面可以做一些IntentService的耗时操作。

image

在onCreate方法里面虽然循环创建了7个IntentService实例,但是真正的实例只有一个。

IntentService 的源码解析

大致流程:

Service启动后首先执行的onCreate方法,在onCreate方法创建了HandlerThread,和ServiceHandler;

不了解HandlerThread可以看这篇文章

ServiceHandler继承自Handler,也就是说onCreate方法里面已经创建了 HandlerThread 和 Handler,
同时注意到用的是HandlerThread的Looper创建的Handler,也就是说Handler的looper和MessageQueue关联在子线程中。

然后Service按照生命周期执行到onStartCommand方法,这里添加了一个自定义的onStart方法,
onStart方法里去通过Handler发送消息,这个Handler就是ServiceHandler;

ServiceHandler 在它的 onHandleMessage方法里,执行onHandleIntent,从上面的介绍可知,onHandleIntent 是个抽象方法需要自己复写。
执行完 onHandleIntent 之后会调用 stopSelf 把服务关闭,也就是不用自己手动关闭。
这里stopSeft是带参数的,和不带参数的方法相比区别是:
带参数的不会立即执行,会等待所有消息处理完之后再终止服务。
不带参数会立即终止。

onHandleMessage 为什么是在子线程运行,也就是onHandleIntent为什么可以做耗时操作:
因为 ServiceHandler 的 looper 对应的是 HandlerThread 的 looper,
一般 Handler 创建在 Activity 中时,采用的是 MainLooper 绑定的是主线程,onHandleMessage 执行在主线程中。
同理 ServiceHandler 绑定的是 HandlerThread 的 looper,HandlerThread 本身就是子线程,
因此 ServiceHandler 的 onHandleMessage 方法运行在子线程,也就是说 onHandleIntent 方法中可以做耗时操作。

处理消息的顺序:
和Handler是一样的,这里的Looper是按照顺序从消息队列中取出任务的,也就是说 IntentServcie 的后台任务执行也是有顺序的。
当有多个后台任务时,这些后台任务也是会按照顺序执行的。

源码就下面几行。

public abstract class IntentService extends Service {
    private volatile Looper mServiceLooper;
    @UnsupportedAppUsage
    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);
}

posted @ 2022-07-07 22:17  cfdroid  阅读(36)  评论(0编辑  收藏  举报