整理之Service
Service
基础
一个Service的基本结构
class MyService : Service() {
private val mBinder = MyBinder()
override fun onCreate() {
super.onCreate()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return super.onStartCommand(intent, flags, startId)
}
override fun onBind(intent: Intent): IBinder {
return mBinder
}
override fun onUnbind(intent: Intent?): Boolean {
return super.onUnbind(intent)
}
override fun onDestroy() {
super.onDestroy()
}
class MyBinder: IBinder() {
//实现对Service的操作,如下载操作的开始暂停等
}
}
<service android:name=".myservice"
android:enabled="true"
android:exported="true"
android:icon="@drawable/background_blue"
android:label="string"
android:process="string"
android:permission="string">
</service>
启动和关闭:启动后无法操作
val intent = Intent(this, MyService::class)
startService(intent)
stop(service)
//每次调用startService都会调用一次onStartCommand,但是onCreate只会调用一次
//只有调用stopService/stopSelf和被系统杀死才会停止服务,startServicec 并不依附于启动它的Context
绑定和解除绑定:可以通过Binder进行操作
private val mBinder = MyService.MyBinder()
private val connection = ServiceConnection() {
@Override
fun onServiceConnected(name: ComponentName, service: IBinder) {
mBinder = service as MyService.MyBinder
}
@Override
onServiceDisconnected(name: ComponentName) { }
}
val intent = Intent(this, MyService::class)
bindService(intent, connection, Service.BIND_AUTO_CREATE)
unbindService(service)
//bindService时不会调用onStartCommand
//当Context不存在后,Service也会终止(配置改变时也会停止Service)
两种启动方式的生命周期:

Android5.0后,隐式启动Service $\color{blue}文字颜色{blue}$
<service
android:name="com.dbjtech.acbxt.waiqin.UploadService"
android:enabled="true" >
<intent-filter android:priority="1000" >
<action android:name="com.dbjtech.myservice" />
</intent-filter>
</service>
val intent = Intent().apply {
setAction("com.android.ForegroundService");
setPackage(getPackageName());//设置应用的包名
}
startService(intent);
粘性服务与非粘性服务
服务的粘性体现在:当服务被系统杀死后,粘性服务会自动重启并执行onStartCommand,非粘性服务不会。
通过onStartCommand的返回值来设置是否粘性,可选择的值为:
| 参数 | 含义 |
|---|---|
| START_STICKY | 如果service进程被kill掉,保留service的状态为开始状态,但不保留递送的intent对象。随后系统会尝试重新创建service,由于服务状态为开始状态,所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传递到service,那么参数Intent将为null。 |
| START_NOT_STICKY | 使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务。 |
| START_REDELIVER_INTENT | 重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。 |
| START_STICKY_COMPATIBILITY | START_STICKY的兼容版本,但不保证服务被kill后一定能重启。 |
默认情况下,通过startService启动的服务为粘性的。
前台服务
官方描述:前台服务是那些被认为用户知道(用户所认可的)且在系统内存不足的时候不允许系统杀死的服务。前台服务必须给状态栏提供一个通知,它被放到正在运行(Ongoing)标题之下——这就意味着通知只有在这个服务被终止或从前台主动移除通知后才能被解除。
使用方法
在onCommand中创建通知
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 在API11之后构建Notification的方式
Notification.Builder builder = new Notification.Builder
(this.getApplicationContext()); //获取一个Notification构造器
Intent nfIntent = new Intent(this, MainActivity.class);
builder.setContentIntent(PendingIntent.
getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(),
R.mipmap.ic_large)) // 设置下拉列表中的图标(大图标)
.setContentTitle("下拉列表中的Title") // 设置下拉列表里的标题
.setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
.setContentText("要显示的内容") // 设置上下文内容
.setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
Notification notification = builder.build(); // 获取构建好的Notification
notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
return super.onStartCommand(intent, flags, startId);
}
启动与停止:
// 参数一:唯一的通知标识;参数二:通知消息。
startForeground(110, notification);// 开始前台服务
stopForeground(true);// 停止前台服务--参数:表示是否移除之前的通知
IntentService
参考这篇文章
1.与Service的区别
Service运行在主线程,内部不能执行耗时操作。但IntentService在执行onCreate 操作的时候,内部开了一个线程,去你执行你的耗时操作
2.特点
会创建独立的 worker 线程来处理所有的 Intent 请求
会创建独立的 worker 线程来处理 onHandleIntent() 方法实现的代码,无需处理多线程问题
所有请求处理完成后,IntentService 会自动停止,无需调用 stopSelf() 方法停止 Service
为 Service 的 onBind() 提供默认实现,返回 null
为 Service 的 onStartCommand 提供默认实现,将请求 Intent 添加到队列中
3.使用
编写类:
class MyIntentService : IntentService("MyIntentService") {
override fun onHandleIntent(intent: Intent?) {
when (intent?.action) {
。。。
}
}
}
注册:
<service android:name="com.example.intentservicetest.MyService" />
启动:
val intent = Intent(MainActivity.this, MyService.class);
startService(intent);
//所有的请求的处理都在一个工作线程中完成 , 它们会交替执行(但不会阻塞主线程的执行),一次只能执行一个请求。
4.执行过程
- 每次启动该服务并不是马上处理你的工作,而是首先会创建对应的Looper、Handler,并且在 MessageQueue 中添加附带客户 Intent 的 Message 对象。
- 当 Looper 发现有 Message 的时候,会在onHandleIntent((Intent)msg.obj) 中得到 Intent 对象,调用你的处理程序,处理完后即会停止自己的服务。
Intent 的生命周期跟你的处理的任务是一致的,所以这个类用下载任务中非常好,下载任务结束后服务自身就会结束退出。
整理之Service的更多相关文章
- Android学习笔记(九)一个例子弄清Service与Activity通信
上一篇博文主要整理了Service的创建.绑定过程,本篇主要整理一下Service与Activity的通信方式.包括在启动一个Service时向它传递数据.怎样改变运行中的Service中得数据和侦听 ...
- 安卓组件service
[转]http://blog.csdn.net/ithomer/article/details/7364024 一. Service简介 Service是android 系统中的四大组件之一(Acti ...
- Service Worker MDN英文笔记
前言: 以前学习基础知识的时候总看别人写的入门文章,但有时候还是一脸懵逼,直到自己用心阅读了MDN的英文文档才对基础知识的一些理论有了更深的理解,所以我在边阅读文档的时候边记录下帮助比较大的,也方便大 ...
- Android Service 服务(三)—— bindService与remoteService
(转自:http://blog.csdn.net/ithomer/article/details/7366396) 一.bindService简介 bindService是绑定Service服务, ...
- android service 整理
项目经常要跟别的项目进行交互,比如说蓝牙打印机等,或者处理一些网络状态,或者调用baidu.高德等地图的时候就会用到, 或打开了音乐播放之后,便想去看看图片,或者下载文件的时候,我们看看博客. Ser ...
- Service Worker基础知识整理
Service Worker是什么 service worker 是独立于当前页面的一段运行在浏览器后台进程里的脚本.它的特性将包括推送消息,背景后台同步, geofencing(地理围栏定位),拦截 ...
- 微服务(Microservices)和服务网格(Service Mesh)架构概念整理
注:文章内容为摘录性文字,自己阅读的一些笔记,方便日后查看. 微服务(Microservices) 在过去的 2016 年和 2017 年,微服务技术迅猛普及,和容器技术一起成为这两年中最吸引眼球的技 ...
- docker常用命令整理-在容器中使用service命令
在docker中使用centos镜像启动了容器并安装了相关软件,之后想用service命令启动相关服务却收到如下错误: Failed to get D-Bus connection: Operatio ...
- (整理)IIS 7 503 "service unavailable" errors
原文地址:http://mvolo.com/where-did-my-iis7-server-go-troubleshooting-503-quotservice-unavailablequot-er ...
随机推荐
- javascript中“==”,“===”和“Object.is(a,b)”的区别
作为两个量比较的三种方式"==","==="和"Object.is(a,b)"有一定区别,如下(具体见MDN): (1)Object.is( ...
- 第九篇 -- 对数据库mysql进行连接并压测(二)
上一节介绍了对mysql查询语句的压测,这一节来进一步的了解. 还是先把数据库的图放上来. 接下来打开Jmeter. 1. 回顾一下上一节学的查询语句 JDBC Request配置 结果 2. 条件查 ...
- intouch制作历史报警查询(时间查询,筛选关键字)
在项目中,intouch制作历史报警查询已属于标配功能,如何做出按时间以及关键字来进行综合查询,提高历史报警查询效率仍然是一个值得研究的问题,接下来参考网上文章自己总结下如何制作. 1.DTPicke ...
- synchronized 加锁 this 和 class 的区别!
synchronized 是 Java 语言中处理并发问题的一种常用手段,它也被我们亲切的称之为"Java 内置锁",由此可见其地位之高.然而 synchronized 却有着多种 ...
- 创建一个计算器的函数calc含有两个数字,调用函数的函数传递一个函数,分别是实现加减乘除
function calc(num){ var n1=8; var n2=2; num(n1,n2); } //加 functiong jia(a,b){ console.log( a+b ); } ...
- Docker限制
前言 Docker系列文章: 此篇是Docker系列的第十篇,大家一定要按照我做的Demo都手敲一遍,印象会更加深刻的,马上就开始Kubernetes,加油!一起前行! 为什么要学习Docker Do ...
- PWN——uaf漏洞学习
PWN--uaf漏洞 1.uaf漏洞原理 在C语言中,我们通过malloc族函数进行堆块的分配,用free()函数进行堆块的释放.在释放堆块的过程中,如果没有将释放的堆块置空,这时候,就有可能出现us ...
- Python 列表解析式竟然支持异步?
PEP原文:https://www.python.org/dev/peps/pep-0530 PEP标题:PEP 530 -- Asynchronous Comprehensions PEP作者:Yu ...
- 神奇的 SQL 之别样的写法 → 行行比较
开心一刻 昨晚我和我爸聊天 我:"爸,你怎么把烟戒了,也不出去喝酒了,是因为我妈不让,还是自己醒悟,开始爱惜自己啦?" 爸:"儿子啊,你说的都不对,是彩礼又涨价了.&qu ...
- Alibaba-技术专区-Dubbo3总体技术体系介绍及技术指南(序章)
Dubbo的背景介绍 Apache Dubbo 是一款微服务开发框架(是一款高性能.轻量级的开源 Java 服务框架),它提供了 RPC通信 与 微服务治理 两大关键能力.这意味着,使用 Dubbo ...