Service内核原理(二):自带工程线的IntentService

为什么要使用IntentService:

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.
�这是摘自IntentService的注释,说明IntentService是一个基于异步请求的抽象类,我们的请求通过startService启动,顾名思义,IntentService会根据传得Intent来在工作线程中处理我们的任务,并且会在任务运行完结束自己。
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.
并且说明了使用的方法,由此看可以看出其使用的是工作队列处理模式,来减轻主线程的负担,其存在的意义就是简化这个流程,通过实现onHandleIntent这个方法,我们就可以轻松的实现相关的操作。

原理解析:

通过上面的文档,可以看出,能实现消息队列的,在Android系统内部,使用的最多的便是looper+handler机制了,所以,其肯定是包含了这个机制的。

那就来逐步分析
  • 成员变量
    private volatile Looper mServiceLooper; private volatile ServiceHandler mServiceHandler; private String mName; private boolean mRedelivery;
    明显的是looper+handler机制,关于mRedelivery这个变量,等等会说到,looper+handler机制原理,后续会写一篇笔记。

  • ServiceHandler 和 onHandleIntent
    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); }}
    这个ServiceHandler是继承自Handler,重写了handleMessage方法,所以我们的任务都是通过这个handler来执行的,因为当handler会在这里执行onHandleIntent()这个抽象方法,并且执行完,会执行service自带的stopSelf()方法,所以文档才说执行完会自动关闭。

  • mRedelivery 和 onStartCommand
    这个变量基本上我们一般不会去动,默认值是false,那他的作用是什么?
    public void setIntentRedelivery(boolean enabled) { mRedelivery = enabled;}

You should not override this method for your IntentService. Instead,* override {@link #onHandleIntent}, which the system calls when the IntentService* receives a start request. public int onStartCommand(Intent intent, int flags, int startId) { onStart(intent, startId); return mRedelivery ? START_REDELIVER_INTENT:START_NOT_STICKY;}
google官方给我们的建议是不要复写这个方法而是去实现onHandleIntent()这个方法,当系统受到请求时就会执行这个onStart方法,这也是我们继承IntentService,执行startService方法而不用复写onStartCommand()方法的原因。说到mRedelivery这个变量,从书面意思就是再发送的意思。
<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.
如果是设置为true,当这个进程在onHandleIntent之前挂掉了,这个进程会重新启动并且重新发送,如果多个intents已发送,只会有一个最近的被重新发送处理。
* <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.*/
如果是false的话,这个intent会随着进程的结束而结束。
一般来说mRedelivery为false,如果我们需要的话我们可以给这个赋值为true。
那关于为什么返回两个标识符会有不同的结果,我大概猜是和stopself和activitymanager中有关,等以后我读到ActivityManager的源码时再来说吧。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7A3yxDOk-1609834050212)(//upload-images.jianshu.io/upload_images/1935371-cb71c8b0e3db35c5.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/960/format/webp)]


继续,下面说最重要的两个方法

  • onCreate 和 onStart
    public void onCreate() { super.onCreate(); HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper);}
    我们终于看清这个IntentService的庐山真面目了,就是封装了对HandlerThread的操作,通过HandlerThread,初始化了消息队列以及开辟了工作线程,执行完start后,获取到该线程的looper对象,再将该looper和自定义的mServiceHandler绑定起来,即可达成消息处理,构成经典的handler+looper机制。关于HandlerThread这个类以及handler+looper机制,我后续会再写笔记。
    @Overridepublic void onStart(Intent intent, int startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg);}
    这个onStart方法是在onStartCommond方法中执行的,就是通过mServiceHandler将activity传过来的intent封装成message来发送至
    mServiceHandler自己处理。

至此

我们基本上已经将IntentService扒光了,由此看出,其实其构造真的不复杂,并且原理好像也是很简单。
这么想想,其实我们平时自己写service时,很多代码都是可以封装的,但是我们却没有养成这个习惯,而是等到别人出了个新的框架或者库,其实我们自己就能实现这些库,只是我们懒罢了。
今天听了云大一席话,感悟颇深,至此,我会坚持写这个系列的笔记的,大家共勉!此文有不足之处,敬请指出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值