Android IntentService vs Service
众所周知,Android中的Service是用于后台服务的,当应用程序被挂到后台的时候,为了保证应用中某些功能仍然可以工作而引入了Service,比如播放音乐。针对service,官方文档有2点重要说明:
1. A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.除非特别说明,否则和应用是在同一个进程中
2. A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors). Service不是一个线程,也就是说service和UI主线程是在同一线程中运行的,因此service不能执行耗时长的处理,防止出现ANR。
因此如果APP需要在service执行长时间处理时,需要起个独立线程来处理该操作。
Android为我们考虑到了这一点,所以提供了IntentService类。IntentService继承于Service,可以认为是开了一个线程来处理事件的service.
IntentService有如下优点:
1. 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. 队列任务按序执行,全部任务结束后会结束自己。
2. 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.
3. 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代码进行分析:
继承自service
public abstract class IntentService extends Service
有一个工作线程,在onCreate中创建该线程
HandlerThread thread = new HandlerThread(“IntentService[” + mName + “]”);
内部通过handler来处理startService发送的消息事件。同样在onCreate函数中创建thread looper和Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
而在每次调用startService时会将任务添加到队列中
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
Handler执行过程为:
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是按照顺序来执行的,全部任务执行完成后工作线程finish。
使用如下:
在manifext.xml中添加声明
然后在调用的地方直接使用:
public void startService() {
Intent intent = new Intent(this, XXXIntentService.class);
startService(intent);
}
public void stopService() {
Intent intent = new Intent(this, XXXIntentService.class);
stopService(intent);
}
其中调用stopService会直接调用IntentService的onDestroy函数,当前正在执行的任务不会暂停,等该任务完成后线程关闭。如果需要立即结束任务,则可以通过设置变量来让当前任务尽快结束。
版权声明:本文为博主原创文章,未经博主允许不得转载。