整理之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 ...
随机推荐
- 解决proto文件生成pb文件时提示(e.g."message")的问题
原因:格式不支持 解决办法:去下个notepad,打开方式选择notepad,文件属性的只读取消掉 打开后会发现最下面显示了文件的格式是unix,utf-8 右键红框处,选择转换为windows格式, ...
- jvm源码解读--14 defNewGeneration.cpp gc标记复制之后,进行空间清理
进入Eden()->clean()函数 void EdenSpace::clear(bool mangle_space) { ContiguousSpace::clear(mangle_spac ...
- 除了Swagger UI,你还能选择 IGeekFan.AspNetCore.RapiDoc
IGeekFan.AspNetCore.RapiDoc 看到博客园上的这个文章,说了下Knife4J,评论里有人推荐RapiDoc,放了几个图,看了下,还不错. 心里 便有个想法,借着上次研究 Kni ...
- 针对不同场景的Python合并多个Excel方法
大家好,我是辰哥~ 在辰哥看来,技术能够减少繁琐工作带来的枯燥,技术+实际=方便.最近辰哥也是在弄excel文件的时候发现手动去整理有点繁琐枯燥,想着技术可以代替我去处理这部分繁琐的工作那何乐而不为呢 ...
- RHCE_DAY06
iptables防火墙 ----匹配及停止 nerfilter/iptables:工作在主机或网络的边缘,对于进出本主机或网络的报文根据事先定义好的检查规则作匹配检测,对于能够被规则所匹配到的报文做出 ...
- 4.10 Python3 进阶 - 迭代器 & 生成器
>>返回主目录 源码 from typing import Iterable, Iterator # 可迭代对象:字符串.列表.元组.字典.集合.range().enumerate()等 ...
- python中两种拷贝目录方法的比较
首先是用python自己的api: shutil.copytree('./build/tested/doc', './build/tested/build/doc') 优点是改变平台时不需要修改代码, ...
- View epub and mobi File on Linux
Calibre has stand-alone ebook viewer "ebook-viewer", start it in terminal: $ ebook-viewer ...
- 用AutoHotkey做汉字到Unicode字符串的转换
要把汉字转换为搜的形式,也就是在汉字的Unicode Big Endian编码前面加"&#x",后面加分号.例如""字转换后为"搜" ...
- 🏆【Java技术专区】「开发实战专题」Lombok插件开发实践必知必会操作!
前言 在目前众多编程语言中,Java 语言的表现还是抢眼,不论是企业级服务端开发,还是 Andorid 客户端开发,都是作为开发语言的首选,甚至在大数据开发领域,Java 语言也能占有一席之地,如Ha ...