IntentService是如何在子线程运行的。

IntentService 是如何让服务运行在子线程的
IntentService是一个继承Service的抽象类。

public abstract class IntentService extends Service {
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;
    .....
    }

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

        @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();
        //工作线程 thread对象在run方法中创建,所以调用thread.start()后,本线程的looper对象和消息队列就创建完成了

        mServiceLooper = thread.getLooper();
        //handled对象关联thread线程中的looper对象 和 消息队列。
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    ```
``
     @Override
    public void onStart(Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }

//服务运行时,handle封装Message对象。加入到
对应的消息队列中,looper对象就会去遍历消息队列
取出Message对象,并调用器msg.target.dispatchMessage(msg);
looper是在运行在子线程中的,所以handler处理消息也是在子线程。这样就实现了把任务添加到工作线程中执行。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值