开启处理耗时操作的方法–IntentService

来源:互联网 发布:java中方法的概念 编辑:程序博客网 时间:2024/06/13 23:15

开启处理耗时操作的方法–IntentService

一、概述

  1. 能解决的问题:

    • 当一个任务分为多个小任务,这些小任务必须按照一定顺序来执行,而且这些任务可能会比较耗时
  2. 为什么选择这个方法:

    • 利用这个方法无需手动控制线程的执行顺序
    • 如果是一个后台任务,交给Service去执行,因为Service中也不能执行耗时操作,所以还是需要开启子线程开执行,使用这个方法就可以忽略这个问题
    • 当任务执行完毕后会自动关闭服务
    • 从Activity中发送Intent之后就可以丢给后台去处理,就算当前的Activity被finish掉也不会影响任务的执行

二、IntentService介绍

public abstract class IntentService extends Service

java.lang.Object    ↳ android.content.Context         ↳ android.content.ContextWrapper             ↳ android.app.Service                  ↳ android.app.IntentService

API原版说明:

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是一个基本类,用来处理异步请求(用Intents来传递的)的服务。客户端通过调用startService(Intent)来发送请求;当需要的时候service被启动,使用一个工作者线程来依次处理每一个Intent;当任务运行完毕之后会自动关闭。

这个“工作队列处理器”模式通常用来帮助处理应用的主线程中的任务。IntentService类是为了简化这个模式和照看结构而存在的。通过继承IntentService实现onHandleIntent(Intent)方法来使用它。IntentService将会接收Intents,创建一个工作者线程,并在适当的时候(任务结束的时候)停止服务。

所有的请求都被一个单独的工作者线程处理–他们或许需要足够长的时间来处理(并且不会阻塞应用的主循环),但是同一时间只能处理一个请求

三、IntentService的使用方法

当然到了最关心的了–用法

  1. 创建一个类,继承IntentService,注意的是这里需要写一个无参的构造方法,不然会报错

    public class HandleTaskService extends IntentService {    // 继承自父类的方法    public HandleTaskService(String name) {        super(name);    }    // 注:这里要添加    public HandleTaskService(){        super("HandleTaskService");    }}
  2. 实现最关键的处理方法

    @Overrideprotected void onHandleIntent(Intent intent) {    // 这里写你的代码处理逻辑}
  3. IntentService继承自Service,所以同样需要到AndroidManifest.xml中去注册

  4. 调用方式:

    Intent intent = new Intent(this, HandleTaskService.class);intent.addFlags(101);intent.putExtra("content", content);startService(intent);

附上生命周期图:

IntentService生命周期

图片出处:http://blog.csdn.net/flowingflying/article/details/7616333

0 0
原创粉丝点击