android 服务耗时,一种更简单的处理耗时任务的方式--IntentService

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

一、概述

能解决的问题:

当一个任务分为多个小任务,这些小任务必须按照一定顺序来执行,而且这些任务可能会比较耗时

为什么选择这个方法:

利用这个方法无需手动控制线程的执行顺序

如果是一个后台任务,交给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的使用方法

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

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

public class HandleTaskService extends IntentService {

// 继承自父类的方法

public HandleTaskService(String name) {

super(name);

}

// 注:这里要添加

public HandleTaskService(){

super("HandleTaskService");

}

}

实现最关键的处理方法

@Override

protected void onHandleIntent(Intent intent) {

// 这里写你的代码处理逻辑

IntentService继承自Service,所以同样需要到AndroidManifest.xml中去注册

调用方式:

Intent intent = new Intent(this, HandleTaskService.class);

intent.addFlags(101);

intent.putExtra("content", content);

startService(intent);

附上生命周期图:

xlxipuw.png

IntentService生命周期

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值