IntentService 使用与源码解析

IntentService 使用与源码解析

IntentService 这兄弟用的地方也蛮多,用起来也蛮顺手, 而且用过不用太操心是否将其关闭。 之前在介绍Handler消息机制一文中简单介绍其工作原理。 本文就着重IntentService进行解析。

本文主要分六部分展开:

  1. IntentService的介绍
  2. IntentService的使用
  3. IntentService的源码解析
  4. IntentService的常见问题
  5. 总结
  6. 参考资料

1. IntentService的介绍

这么说吧如果有一个任务,可以分成很多个子任务,需要按照顺序来完成,如果需要放到一个服务中完成,那么使用IntentService是最好的选择。

一般情况下我们所使用的Service是运行在主线程当中的,所以在service里面编写耗时的操作代码,则会卡主线程会ANR。为了解决这样的问题,谷歌引入了IntentService.

IntentService是自己维护了一个线程,来执行耗时的操作,然后里面封装了HandlerThread,能够方便在子线程创建Handler。

IntentService是继承自Service用来处理异步请求的一个基类,客户端startService发送请求,IntentService就被启动,然后会在一个工作线程中处理传递过来的Intent,当任务结束后就会自动停止服务。

2. IntentService的使用

IntentService的使用十分简单,分为下面几个步骤:

  • 新建子类继承IntentService,在AndroidManifest注册该Service, 复写onHandleIntent方法并在onHandleintent方法中进行异步操作
  • 一般在Activity中调用IntentService,与使用普通Service类似,不过不要使用绑定方式,而要使用startService启动,并在Intent中放入相应的数据
  • 使用Handler或者本地广播等手段将onHandleIntent异步执行结果传给主线程
  • 主线程获取到异步操作结果并对其进行处理和展示等等

具体的使用方法就不粘贴了, 网上代码一搜一大把。

3. IntentService的源码解析

源码解析, 鉴于 IntentService 一共也没多少行,索性都粘出来 。

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.
     *
     从字面理解是设置intent重投递。如果设置为true,
     onStartCommand(Intent, int, int)将会返回START_REDELIVER_INTENT,
     如果onHandleIntent(Intent)返回之前进程死掉了,那么进程将会重新启动,intent重新投递,
     如果有大量的intent投递了,那么只保证最近的intent会被重投递。
     
     */
    public void setIntentRedelivery(boolean enabled) {
        mRedelivery = enabled;
    }

    /// Service的onCreate 被调用时 即创建 handlerThread  , 将HandlerThread的Looper 与ServiceHandler关联。 
    //// 至此 ServiceHandler 与异步的子线程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);
    }

    @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
     *  启动 除了第一次 调用onCreate 方法 关联HandlerThread 与ServiceHandler . 其后 再次调用 则会调用onStartCommand 方法 。
     
     该方法 内部会调用onStart方法 。 而同时会把startID传递进入Message  ,将Intent 作为 message之obj  包装后 发送 。 
     
     IntentService 是一种non-sticky 服务,non-sticky 服务在服务自己认为完成任务时停止,为了获得non-sticky 服务,应返回 START_REDELIVER_INTENT 或者 START_NOT_STICKY,而二者的区别则是如果系统需要在服务完成任务之前关闭它,则服务的具体表现不同,START_NOT_STICKY会被关闭,而START_REDELIVER_INTENT则会在系统可用资源不吃紧时,尝试再次启动。
     
     */
    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

        /// Looper  quit 之后 该Looper便停止 循环。 同时Service销毁。 
         
    @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.
     
     当在onStart方法中,通过sendMessage方法将Message放入到Handler所关联的消息队列中后,Handler所关联的Looper对象会从消息队列中取出一个Message,然后将其传入Handler的handleMessage方法中,在handleMessage方法中首先通过Message的obj获取到了原始的Intent对象,然后将其作为参数传给了onHandleIntent方法让其执行。
     handleMessage方法是运行在HandlerThread的,所以onHandleIntent也是运行在工作线程中的。
     在执行完了onHandleIntent之后,我们需要调用stopSelf(startId)声明某个job完成了。
     当所有job完成的时候,Android就会回调onDestroy方法,销毁IntentService。
     */
    @WorkerThread  ///////  该方法为工作线程  也就是再HandlerThread中被调用。 
    protected abstract void onHandleIntent(@Nullable Intent intent);
}

HandlerThread的源码解析就不再赘述了, 如有想要深入了解的可查看我的另一篇文章 Android Handler消息机制解析中的HandlerThread 部分。 算了再简单把注释粘一下。

public class HandlerThread extends Thread {

    //线程优先级
    int mPriority;
    int mTid = -1;
    Looper mLooper;

    public HandlerThread(String name) {
        super(name);
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }
    

    public HandlerThread(String name, int priority) {
        super(name);
        mPriority = priority;
    }
    

    protected void onLooperPrepared() {
    }

    @Override
    public void run() {
        //获取进程ID
        mTid = Process.myTid();
        //Loopr准备
        Looper.prepare();
        //创建Looper
        synchronized (this) {
            mLooper = Looper.myLooper();
            //唤醒所有等待的线程
            notifyAll();
        }
        //设置线程优先级
        Process.setThreadPriority(mPriority);
        //在Looper循环时做一些准备工作
        onLooperPrepared();
        //开启循环
        Looper.loop();
        mTid = -1;
    }
    
 
    public Looper getLooper() {
        //如果线程已经消亡,就返回null
        if (!isAlive()) {
            return null;
        }
        //如果线程已经创建了,就在此处停留等待Looper创建完成之后
        synchronized (this) {
            while (isAlive() && mLooper == null) {
                //等待线程被创建
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }

    public boolean quit() {
        //获取looper
        Looper looper = getLooper();
        if (looper != null) {
            //退出looper
            looper.quit();
            return true;
        }
        return false;
    }

    //安全退出
    //跟quit方法的唯一区别在于looper.quit()变成了looper.quitSafely()
    public boolean quitSafely() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quitSafely();
            return true;
        }
        return false;
    }

    /**
     * Returns the identifier of this thread. See Process.myTid().
     */
    public int getThreadId() {
        return mTid;
    }
}

4. IntentService的常见问题

a. 如果启动IntentService多次,会出现什么情况呢?

IntentService多次被启动,那么onCreate()方法只会调用一次,所以只会创建一个工作线程。但是会调用多次onStartCommand方法,只是把消息加入消息队列中等待执行

b. 多次开启intentService,那为什么工作任务队列是顺序执行的?

当我们通过startService多次启动了IntentService,这会产生多个job,由于IntentService只持有一个工作线程,所以每次onHandleIntent只能处理一个job。面多多个job,IntentService会如何处理?处理方式是one-by-one,也就是一个一个按照先后顺序处理,先将intent1传入onHandleIntent,让其完成job1,然后将intent2传入onHandleIntent,让其完成job2…这样直至所有job完成,所以我们IntentService不能并行的执行多个job,只能一个一个的按照先后顺序完成,当所有job完成的时候IntentService就销毁了,会执行onDestroy回调方法。

5. 总结

IntentService的优点

  1. 它创建一个独立的工作线程来处理所有一个一个intent。
  2. 创建了一个工作队列,来逐个发送intent给onHandleIntent()
  3. 不需要主动调用stopSelf()来结束服务,因为源码里面自己实现了自动关闭。
  4. 默认实现了onBind()返回的null。
  5. 默认实现的onStartCommand()的目的是将intent插入到工作队列。

IntentService使用场景

  1. IntentService不需要我们自己去关闭Service,它自己会在任务完成之后自行关闭,不过每次只能处理一个任务,所以不适用于高并发,适用于请求数较少的情况。
    类似于APP的版本检测更新、 定位功能、同步通讯录、 笔记应用的笔记列表 资源同步以及 读取少量的IO操作。
  2. 推送Service 例如 阿里的推送Service就是 集成自IntentService 。
  3. 还可以将 应用的初始化, 例如MultiDex中dex的异步加载, 资源文件的异步加载等。

6. 参考资料

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