IntentService使用

看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,称为work thread,再看 HandlerThread的run方法

    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

通过其run方法可以看出 HandlerThread已经是一个异步消息处理线程了。

ServiceHandler是用来往HandlerThread的消息队列中发送消息,并用来处理消息

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

再看onStart方法

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

当startService(intent)开启服务,传来intent后,在onStart方法中,通过ServiceHandler传给HandlerThread所拥有的消息队列,然后 HandlerThread取出该消息,调用ServiceHandler的handleMessage方法,在handleMessage方法中,ServiceHandler调用onHandleIntent((Intent)msg.obj)方法。


Service,IntentService,AsyncTask比较

Service用来处理耗时任务,可以常驻后台运行。

IntentService是Service的子类,它的特点是可以用来处理异步任务,当然该任务可以是耗时任务,而且可以处理多个异步任务,单同时只能处理一个,因为只有一个work thread,当处理完任务后,自己会停止。

AsyncTask也可以用来处理耗时任务,它的好处是和Ui线程交互起来很方便,不同的方法工作在不同的线程中,方法的执行顺序是规定好的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值