android服务销毁线程,017 Android多线程-IntentService-使用

前言

IntentServcie作为Service的一个子类,可以看做是Service和HandlerThread的结合体,在完成了使命之后会自动停止,适合需要在工作线程处理UI无关任务的场景。那么今天就来讲讲IntentServcie的相关知识吧。

今天涉及的知识点:

IntentService特点

IntentService工作流程

IntentService使用步骤

IntentService的使用

IntentService注意项

WorkService后台处理效果图和项目结构图

WorkService 和 MainActivity中使用源码

先来波运行效果图

c74685882d9f

image

一.IntentService特点

IntentService 是继承自 Service 并处理异步请求的一个类,在 IntentService 内有一个工作线程来处理耗时操作。

任务执行完毕后,IntentService会自动销毁,不需要我们去手动处理

如果IntentService启动多次,每个耗时操作会以队列形式在IntentService 的 onHandleIntent方法中依次执行,串行执行方式结束后,IntentService自动销毁。

二.IntentService工作流程

IntentService工作流程流程如下:

c74685882d9f

image

三. IntentService使用步骤

IntentService使用步骤如下:

新建service类并继承自IntentService

实现service的构造方法

在manifast.xml中注册服务

在服务的onHandleIntent方法中实现业务逻辑

四.IntentService的使用

下面以一个例子讲解IntentService的使用。

4.1 新建WorkService继承自IntentService

代码如下:

public class WorkService extends IntentService {

public WorkService() {

//必须实现父类的构造方法

super("WorkService");

}

@Override

protected void onHandleIntent(@Nullable Intent intent) {

}

}

这里需要注意的是,必须实现WorkService的构造方法,然后一般在 super方法中写入但当前servcie的类名,以作标志。

4.2 manifast.xml中注册WorkService

IntentService作为Service的子类,但仍然是一个Service,所以我们需要在manifast.xml中注册服务:

//其他代码省略

//......

>

//其他代码省略

//......

这里需要注意的是 service标签中和action标签中的name属性要保持唯一性,我一般用当前service类的全路径表示。

4.3 在MainActivity中启动WorkService

一切弄好后,就开始在MainActivity中启动WorkService了,在MainActivity中启动主要代码如下:

//所有的耗时任务都将在onHandleIntent中处理

Intent intent=new Intent(MainActivity.this, WorkService.class);

intent.putExtra("taskId",1);

startService(intent);

五 IntentService注意项

IntentService使用时需要注意的是:

如果IntentService启动多次,每个耗时操作会以队列形式在IntentService 的 onHandleIntent方法中依次执行,串行执行方式结束后,IntentService自动销毁。

IntentService的启动要使用"非绑定模式",若以“绑定”模式启动,将不会走IntentService的onHandleIntent方法,所以要以"非绑定模式"启动

六 WorkService后台处理效果图和项目结构图

效果图

c74685882d9f

image

项目结构图

c74685882d9f

image

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值