Android IntentService工作原理

IntentService与普通的Service最大的区别在于,通过startService启动的普通Service,如果不主导调stopService方法,那么这个service会在后台一直存在。 而通过startService启动的IntentService,他在执行完所有异步任务后,会自己销毁。

通过查看源码,我们知道 IntentService 实际上是继承了Service类的,他与普通Service不同的是,它定义了一个ServiceLooper和ServiceHandler。


当我们启动一个IntentService的时候,首先会进入Service的onCreate方法,我们来看看IntentService在onCreate方法里都做了些什么。

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

从代码中可以看到,它创建一个HandlerThread的线程,然后直接启动这个线程,
然后再初始化上面说的mServiceLooper和mServiceHandler.(如果不知道handler,looper工作原理的自行查阅)。

mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);//handler使用的looper是HandlerThread里的,
//也就是说使用该handler发送的消息都会到 HandlerThread 的 Looper的 MessageQueue中。

在HandlerThread的run方法中,Looper.loop() 进入循环等待mServiceHandler发送的消息


image.png


当有消息会回调到mServiceHandler的handleMessage方法中,在这里

        @Override
        public void handleMessage(Message msg) {
            onHandleIntent((Intent)msg.obj);
            stopSelf(msg.arg1);
        }

有一个抽象方法 onHandleIntent 去处理异步任务,同时会调用stopSelf(msg.arg1);去停止服务,但是这个服务不是直接停止,需要等所有的异步任务 处理完成之后才会去销毁自己。 待会我们用代码去验证这一点。
当IntentService中所有的异步任务都执行完成后,会销毁掉。 那我们启动的HandlerThread什么时候销毁呢,如果不销毁每启动一次IntentService创建个异步线程,那显然是不合理的。 关键就在于IntentSerice的 onDestory方法。

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

对应到looper中的quit方法

    /**
     * Quits the looper.
     * <p>
     * Causes the {@link #loop} method to terminate without processing any
     * more messages in the message queue.
     * </p><p>
     * Any attempt to post messages to the queue after the looper is asked to quit will fail.
     * For example, the {@link Handler#sendMessage(Message)} method will return false.
     * </p><p class="note">
     * Using this method may be unsafe because some messages may not be delivered
     * before the looper terminates.  Consider using {@link #quitSafely} instead to ensure
     * that all pending work is completed in an orderly manner.
     * </p>
     *
     * @see #quitSafely
     */
    public void quit() {
        mQueue.quit(false);
    }

这样,looper就退出循环了。HandlerThread run方法执行完也就销毁了。

下面通过例子来看,定义一个IntentService:

public class MyIntentService extends IntentService {

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

    @Override
    public void onStart(@Nullable Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.i("dx startId",String.valueOf(startId));
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.i("dx", String.valueOf(Thread.currentThread().getId()));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("dx onDestroy","onDestroy");
    }
}

我们在onHandleIntent 让工作线程停止两秒来模拟耗时任务,然后打印出当前工作线程的pid。

在activity中定义一个图片的点击事件,每点击一次,启动一次IntentService

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,MyIntentService.class);
                startService(intent);
            }
        });

我们点击一次。


image.png

可以看到,Service的销毁是在异步任务结束之后才销毁的。

我们再快速连续点击三次,启动三次Service:

image.png

通过log我们可以看到,当service启动后,如果它还在执行异步任务,没有销毁,你再次启动它,他是不会走onCreate方法的。 因为这三次打印出来的pid都是同一个,说明HandlerThread 还是第一次new出来的那个。 当过了6秒,三个异步任务都执行完之后,我们的IntentService才销毁。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 228,156评论 6 531
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 98,401评论 3 415
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 176,069评论 0 373
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 62,873评论 1 309
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 71,635评论 6 408
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 55,128评论 1 323
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 43,203评论 3 441
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,365评论 0 288
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 48,881评论 1 334
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 40,733评论 3 354
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 42,935评论 1 369
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,475评论 5 358
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,172评论 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 34,582评论 0 26
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 35,821评论 1 282
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 51,595评论 3 390
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 47,908评论 2 372

推荐阅读更多精彩内容