• IntentService用法


    IntentService 用完即走

        IntentService,可以看做是Service和HandlerThread的结合体,在完成了使命之后会自动停止,适合需要在工作线程处理UI无关任务的场景。

    • IntentService 是继承自 Service 并处理异步请求的一个类,在 IntentService 内有一个工作线程来处理耗时操作。
    • 当任务执行完后,IntentService 会自动停止,不需要我们去手动结束。
    • 如果启动 IntentService 多次,那么每一个耗时操作会以工作队列的方式在 IntentService 的 onHandleIntent 回调方法中执行,依次去执行,使用串行的方式,执行完自动结束。

    IntentService继承自Service,内部有一个HandlerThread对象。

        在onCreate的时候会创建一个HandlerThread对象,并启动线程。紧接着创建ServiceHandler对象,ServiceHandler继承自Handler,用来处理消息。ServiceHandler将获取HandlerThread的Looper就可以开始正常工作了。

        每启动一次onStart方法,就会把数消息和数据发给mServiceHandler,相当于发送了一次Message消息给HandlerThread的消息队列。mServiceHandler会把数据传个onHandleIntent方法,onHandleIntent是个抽象方法,需要在IntentService实现,所以每次onStart方法之后都会调用我们自己写的onHandleIntent方法去处理。处理完毕使用stopSelf通知HandlerThread已经处理完毕,HandlerThread继续观察消息队列,如果还有未执行玩的message则继续执行,否则结束。

    启动 IntentService 为什么不需要新建线程?

    IntentService内部的HandlerThread 继承自 Thread,内部封装了 Looper,在这里新建线程并启动,所以启动 IntentService 不需要新建线程。

    为什么不建议通过 bindService() 启动 IntentService?

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

        IntentService 源码中的 onBind() 默认返回 null;不适合 bindService() 启动服务,如果你执意要 bindService() 来启动 IntentService,可能因为你想通过 Binder 或 Messenger 使得 IntentService 和 Activity 可以通信,这样那么 onHandleIntent() 不会被回调,相当于在你使用 Service 而不是 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 不会重新创建新的服务和新的线程,只是把消息加入消息队列中等待执行,而如果服务停止,会清除消息队列中的消息,后续的事件得不到执行。

    原文:https://blog.csdn.net/iromkoear/article/details/63252665

  • 相关阅读:
    Java实现 LeetCode 416 分割等和子集
    Java实现 LeetCode 416 分割等和子集
    在Linux运行期间升级Linux系统(Uboot+kernel+Rootfs)
    【详解】嵌入式开发中固件的烧录方式
    嵌入式系统烧写uboot/bootloader/kernel的一般方法
    Linux下USB烧写uImage kernel
    Xmanager连接CentOS的远程桌面
    命令行利器Tmux
    u-boot中分区和内核MTD分区关系
    uboot环境变量与内核MTD分区关系
  • 原文地址:https://www.cnblogs.com/bluestorm/p/9144943.html
Copyright © 2020-2023  润新知