7. If you want to carry on a long-running task, what do you need to do?

IntentService;Service

Service:执行的操作,依然是在UI线程中执行;如果是耗时的操作,或者是阻塞的操作,那么,会阻塞UI线程,造成ANR现象的出现。

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Each service class must have a corresponding <service> declaration in its package's AndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().

Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work. More information on this can be found in Processes and Threads. The IntentService class is available as a standard implementation of Service that has its own thread where it schedules its work to be done.

IntentService: 会创建一个自己的独立线程,区别于UI线程。这样,任何耗时的操作,都可以通过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的源码:
在使用的时候,只需要定义一个构造函数,提供一个Name;然后,重写onHandleIntent(Intent)方法,在该方法中,可以写上耗时操作,会导致阻塞的操作。
然后,就可以了。按照使用Service那样使用。但是,耗时操作时放到onHandleIntent(Intent)中。
因为,该方法是在独立线程中执行的,不会影响到UI线程。
-----从下面IntentService的实现可知。
-----如果,有多个耗时操作的执行请求,发送给该IntentService来执行,那么,如何处理呢?
因为,只是创建了一个IntentService,对应只是创建了一个Thread;每次发出执行请求,
系统都会回调该方法:
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
也就是,每个执行请求(Intent),变成了每个Message。

每个Message的实际处理,由派生类中的onHandleIntent方法来执行。
所以,即使有多个耗时操作的执行请求,但是每次该IntentService每次只执行一个耗时操作。

IntentService的源码:

package android.app;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;

/**
* An abstract {@link Service} that serializes the handling of the Intents passed upon service
* start and handles them on a handler thread.
*
* <p>To use this class extend it and implement {@link #onHandleIntent}. The {@link Service} will
* automatically be stopped when the last enqueued {@link Intent} is handled.
*/
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;

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

public IntentService(String name) {
super();
mName = name;
}

@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();

mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}

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

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

@Override
public IBinder onBind(Intent intent) {
return null;
}

/**
* Invoked on the Handler thread with the {@link Intent} that is passed to {@link #onStart}.
* Note that this will be invoked from a different thread than the one that handles the
* {@link #onStart} call.
*/
protected abstract void onHandleIntent(Intent intent);
}

最新文章

  1. 轻量级ORM框架——第一篇:Dapper快速学习
  2. hdu2005第几天?
  3. python os.path模块
  4. Docker实践:运行Python应用
  5. spark 特殊函数
  6. 使用shell测试cdn状态
  7. linux下的module_param()解释【转】
  8. static和const关键字
  9. dword word byte 相互转换 .xml
  10. selenium python 定位一组对象
  11. Android之标签选项卡
  12. javascript笔记——密码组合规则
  13. Oracle安装时先决条件检查失败的解决方案
  14. poj 3667 Hotel
  15. linux下切割catalina.out文件,按天生成文件
  16. 怎样通过css的media属性,适配不同分辨率的终端设备?
  17. 模拟IIC协议时序
  18. shell 脚本浅入
  19. Linux下自动备份MySQL
  20. Loadrunner初学

热门文章

  1. Pipeline组项目Postmortem
  2. java多线程三之线程协作与通信实例
  3. requests保持cookies的问题
  4. java基础--逻辑运算符-- 002
  5. python json 序列化
  6. go的IO函数,整理下最基本的IO处理函数,工欲善其事必先利其器
  7. hdu 2962 Trucking (最短路径)
  8. JS执行上下文(执行环境)详细图解
  9. Oracle 以某字段分组,以某字段排序,取前几条
  10. [LOJ #6433]「PKUSC2018」最大前缀和