IntentService使用

来源:互联网 发布:久其软件财务报表 编辑:程序博客网 时间:2024/06/08 20:09

看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线程交互起来很方便,不同的方法工作在不同的线程中,方法的执行顺序是规定好的。


0 0
原创粉丝点击