关于IntentService和Service

来源:互联网 发布:淘宝网页制作软件 编辑:程序博客网 时间:2024/05/18 09:20

如果只是启动一个比较耗时的service做事,可以考虑使用IntentService代替Service,如下:

说明 XXX代表某个自定义的类:

 startService(new Intent(this, XXXService.class));  如果XXXService中太耗时,可能会出现ANR,但是如果使用 startService(new Intent(this, XXXIntentService.class))的时候,则不会出现那种情况,即使XXXIntentService中做了很耗时的操作。

需要说明的是IntentService 继承自Service,关于IntentService的说明见下:

/**
 * IntentService is a base class for {@link Service}s that handle asynchronous
 * requests (expressed as {@link Intent}s) on demand.  Clients send requests
 * through {@link android.content.Context#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.
 *
 * <p>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 {@link #onHandleIntent(Intent)}.  IntentService
 * will receive the Intents, launch a worker thread, and stop the service as
 * appropriate.
 *
 * <p>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.
 *
 */

特点:顺序执行,不阻塞UI线程,可以执行耗时操作