IntentServie源码解析

来源:互联网 发布:淘宝购物车的东西少了 编辑:程序博客网 时间:2024/05/16 12:58

IntentService是Service的子类,默认Service运行在应用所在进程的主线程中,如果要在后台执行耗时任务,需要创建子线程,IntentService即可以满足这样的需求,它封装了一个work-thread,处理接收到的Intent,它可以处理多个请求,但一次只能处理一个。


下面看下它的源码。

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

IntentService的构造方法,IntentService的实现类的构造方法需要调用该构造方法,向其传递一个name,该name用于命名worker-thread,debug时用得着。


    @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实例,并start它,然后HandlerThread从其MessageQueue中轮寻消息,有则处理,没有则等待。创建ServiceHandler的实例,当HandlerThread取到消息,其会回调ServiceHandler的handleMessage()方法。

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

ServiceHandler的handleMessage()方法实现中,其调用了onHandleIntent(),该方法即是IntentService的子类必须实现的方法,onHandleIntent()最终会在worker-thread中执行,当onHandleIntent()返回,调用stopSelf(intstartId)方法,如果startId是最新startService()的id,就停掉服务,如果不是,则不停,等待其他request完成。

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

在onStart()方法中用ServiceHandler向worker-thread发消息。

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

当服务被销毁时停掉worker-thread。

0 0
原创粉丝点击