IntentService解析

来源:互联网 发布:有20个usb端口的电脑 编辑:程序博客网 时间:2024/06/12 01:02


    IntentService使用一个工作队列来从Application的主线程中分担任务,这些任务往往做着比较耗时的工作。IntentService维护着一个工作线程消息处理对象(Handler),通过在工作线程中创建消息循环(Looper)和消息队列(MessageQueue)来以队列的方式处理任务,一次只能处理一个任务,上一个任务请求完成后才接着处理下一个任务请求。

    IntentService继承自Service,也就是说IntentService具有Service的一切特性。客户端可以通过startService(Intent)   来发送一个任务请求,如果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);
    }


    在onCreate()方法中会启动工作线程(HandlerThread)并获取工作线程的消息循环对象(Looper),接着实例化处理工作线程消息队列中消息的Handler对象(ServiceHandler)。做好以上准备工作后,在onStart(Intent intent, int startId) 方法中发送一条任务消息请求 ,接着就是在ServiceHandler中进行消息处理了
     @Override
    public void onStart(Intent intent, int startId) {
        Message msg = mServiceHandler .obtainMessage();
        msg. arg1 = startId;
        msg. obj = intent;
        mServiceHandler .sendMessage(msg);
    }

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


    我们可以看到只要覆写onHandleIntent(Intent)方法来处理耗时的任务就行了。不难发现IntentService正是通过工作线程的消息循环(Looper)来消费客户端发来的任务请求(存储在工作线程消息队列中(MessageQueue))

    IntentService继承自Service,拥有Service的一切特性。IntentService内部发送和消费任务请求(由工作线程的消息循环和消息队列来处理)。更多的细节还应该仔细看看IntentService和HandlerThread的源码