Android:Service 之 IntentService(上)

       Service和其他的应用组件一样,运行在程序的主线程(UI线程),如果我们在Service中进行很多耗时或者阻塞的操作时,程序有可能会被挂起(ANR)。所以需要在Service中开启子线程进行处理,Android SDK为我们提供了一个处理异步工作的Service子类:IntnetService。

      关于IntentService,官方文档是这样说明的:     

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.


      下面为IntentService的部分源码:

public abstract class IntentService extends Service {

        private volatile Looper mServiceLooper;
        private volatile ServiceHandler mServiceHandler;

        private String mName;
        private boolean mRedelivery;
    

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

        }
    
      由源码可以看出,IntentService是Service、HandlerThread和Handler强强联合的产物 。既有服务的功能,还包括处理和循环消息的功能。

      下面为 onCreate() 源码:

@Override
        public void onCreate() {
                super.onCreate();

                HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
                thread.start();

                mServiceLooper = thread.getLooper();
                mServiceHandler = new ServiceHandler(mServiceLooper);
        }
      
       可见IntentService在创建的时候,会开启HandlerThread线程,并获取其Looper对象赋值给IntentSrevice的mServiceLooper。然后用mServiceLooper初始化了mServiceHandler。

       下面为onStart() 源码:

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

                mServiceHandler.sendMessage(msg);
        }

       当IntentService启动时,就会产生一个附带了startID和Intent的Message,并把该Message发送到MessageQueue中。当Looper发现MessageQueue中有消息的时候,就会停止Handler并处理消息,处理的代码如下:

 @Override
        public void handleMessage(Message msg) {
                        onHandleIntent((Intent)msg.obj);
                        stopSelf(msg.arg1);
        }

      其中的 onHandlerIntent((Intent)msg.obj) 方法为抽象方法,在继承IntentService的时候需要重写该方法,用来处理自定义的任务。当指定的任务完成时,就会调用stopSelf(msg.arg1)来结束指定的工作(stopSelf不可以自己调用)。

   当所有的工作都完成时,会执行onDestory()方法:

  @Override
        public void onDestroy() {
                mServiceLooper.quit();
        }
   mServiceLooper.quit() 停止Looper,服务结束。


小结:

      IntentService是基于消息的服务。服务启动后,IntentService会开启worker线程来顺序处理intent的任务。一个intentService可以处理多个任务,只不过是一个接着一个的顺序来处理。并且在处理完所有的任务时,服务会自动关闭,很时候用来处理下载任务。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值