当前位置: 首页 > news >正文

Android 启动service(Kotlin)

一、使用startForegroundService()或startService()启用service

**Activity

 //启动service
val intent: Intent = Intent(ServiceActivity@this,MyService::class.java)
//Build.VERSION_CODES.O = 26
// Android8以后,不允许后台启动Service
if(Build.VERSION.SDK_INT >= 26){startForegroundService(intent)}else{startService(intent)}

 **Service

package com.example.buju.serviceimport android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompatclass MyService:Service() {override fun onCreate() {super.onCreate()Log.e("MyService","onCreate")initNotification()}// 初始化通知(安卓8.0之后必须实现)private fun initNotification() {val channelName = "channelName"val channelId = "channelId"if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){// 发送通知,把service置于前台val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager// 从Android 8.0开始,需要注册通知通道if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)notificationManager.createNotificationChannel(channel)}// 页面跳转val intent = Intent(applicationContext,ServiceActivity::class.java)val pendingIntent = PendingIntent.getActivity(this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT)// 创建通知并配置相应属性val notification = NotificationCompat.Builder(this, channelId).setSmallIcon(android.R.drawable.star_off)//小图标一定需要设置,否则会报错(如果不设置它启动服务前台化不会报错,但是你会发现这个通知不会启动),如果是普通通知,不设置必然报错.setLargeIcon(BitmapFactory.decodeResource(getResources(), android.R.drawable.star_on)).setContentTitle("通知标题")// 标题.setContentText("通知内容")// 内容.setPriority(NotificationCompat.PRIORITY_DEFAULT).setContentIntent(pendingIntent)// 设置跳转.setWhen(System.currentTimeMillis()).setAutoCancel(false).setOngoing(true).build()// 注意第一个参数不能为0startForeground(1, notification)}}override fun onBind(intent: Intent?): IBinder? {Log.e("MyService","onBind")return null}override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {Log.e("MyService","onStartCommand")return super.onStartCommand(intent, flags, startId)}override fun onUnbind(intent: Intent?): Boolean {Log.e("MyService","onUnbind")return super.onUnbind(intent)}override fun onDestroy() {super.onDestroy()Log.e("MyService","onDestroy")//停止的时候销毁前台服务。stopForeground(true);}}

注意该方法不会调用onBind()和onUnbind()

二、绑定启用service

**Activity

package com.example.bujuimport android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.example.buju.service.MyServiceclass ServiceActivity:AppCompatActivity() {private var myBinder:MyService.MyBinder? = nulllateinit var startBtn:Buttonlateinit var stopBtn:Buttonlateinit var getBtn:Buttonoverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_service)initControls()}/*** 控件初始化* */private fun initControls(){startBtn = findViewById(R.id.startBtn)startBtn.setOnClickListener(btnClick)stopBtn = findViewById(R.id.stopBtn)stopBtn.setOnClickListener(btnClick)getBtn = findViewById(R.id.getBtn)getBtn.setOnClickListener(btnClick)}/*** service 连接* */private val connection = object:ServiceConnection{//Activity与Service连接成功时回调该方法override fun onServiceConnected(name: ComponentName?, service: IBinder?) {Log.e("MyService","---------Service 成功连接----------")myBinder = service as MyService.MyBinder}// Activity与Service断开连接时回调该方法override fun onServiceDisconnected(name: ComponentName?) {Log.e("MyService","---------Service 断开连接----------")}}/*** 点击事件* */val btnClick:(View)->Unit = {when(it.id) {R.id.startBtn -> {// 绑定serviceval intent: Intent = Intent(ServiceActivity@this,MyService::class.java)bindService(intent,connection,Context.BIND_AUTO_CREATE)}R.id.stopBtn ->{// 解除绑定unbindService(connection)}R.id.getBtn ->{// 获取service传递过来的数据Log.e("MyService","getCount=${myBinder?.getCount()}")}else ->{}}}override fun finish() {super.finish()overridePendingTransition(R.anim.slide_no,R.anim.slide_out_from_bottom)}override fun onDestroy() {super.onDestroy()// 解除绑定unbindService(connection)}}

**Service

package com.example.buju.serviceimport android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompatclass MyService:Service() {/*** 用于传递参数* */private var count:Int = 0private var myBinder:MyBinder = MyBinder()inner class MyBinder: Binder(){fun getCount():Int?{return count}}override fun onCreate() {super.onCreate()Log.e("MyService","onCreate")Thread(Runnable {Thread.sleep(1000)count=100}).start()initNotification()}// 初始化通知(安卓8.0之后必须实现)private fun initNotification() {val channelName = "channelName"val channelId = "channelId"if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){// 发送通知,把service置于前台val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager// 从Android 8.0开始,需要注册通知通道if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)notificationManager.createNotificationChannel(channel)}val notification = NotificationCompat.Builder(this, channelId).setSmallIcon(android.R.drawable.star_off)//小图标一定需要设置,否则会报错(如果不设置它启动服务前台化不会报错,但是你会发现这个通知不会启动),如果是普通通知,不设置必然报错.setLargeIcon(BitmapFactory.decodeResource(getResources(), android.R.drawable.star_on)).setContentTitle("通知标题")// 标题.setContentText("通知内容")// 内容.setWhen(System.currentTimeMillis()).setAutoCancel(false).setOngoing(true).build()// 注意第一个参数不能为0startForeground(1, notification)}}override fun onBind(intent: Intent?): IBinder? {Log.e("MyService","onBind")return myBinder}override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {Log.e("MyService","onStartCommand")return super.onStartCommand(intent, flags, startId)}override fun onUnbind(intent: Intent?): Boolean {Log.e("MyService","onUnbind")return super.onUnbind(intent)}override fun onDestroy() {super.onDestroy()Log.e("MyService","onDestroy")//停止的时候销毁前台服务。stopForeground(true);}}

相关文章:

Android 启动service(Kotlin)

一、使用startForegroundService()或startService()启用service **Activity //启动service val intent: Intent Intent(ServiceActivitythis,MyService::class.java) //Build.VERSION_CODES.O 26 // Android8以后,不允许后台启动Service i…...

Windows蓝牙驱动开发之模拟HID设备(一)(把Windows电脑模拟成蓝牙鼠标和蓝牙键盘等设备)

by fanxiushu 2024-03-14 转载或引用请注明原作者 把Windows电脑模拟成蓝牙鼠标和蓝牙键盘,简单的说,就是把笨重的PC电脑当成鼠标键盘来使用。 这应该是一个挺小众的应用,但有时感觉也应该算比较好玩吧, 毕竟实现一种一般人都感觉…...

LlamaParse: 高效的PDF文件RAG解析工具

LlamaParse: 高效的PDF文件RAG解析工具 通过Thomas Reid的深入探索,LlamaParse成为了目前我所见最优秀的RAG实现用PDF解析器。基于AI的技术,尤其在处理像SEC Q10这样的复杂文件时表现出色,这些文件通常包含文本、数字及其组合构成的表格&…...

platform设备注册驱动模块的测试

一. 简介 上一篇文章编写了 platform设备注册代码,文章地址如下: 无设备树platform驱动实验:platform设备注册代码实现-CSDN博客 本文继续无设备树platform驱动实验,本文对编译好的 设备注册程序进行测试,测试所实…...

鸿蒙Harmony应用开发—ArkTS声明式开发(容器组件:ListItemGroup)

该组件用来展示列表item分组,宽度默认充满List组件,必须配合List组件来使用。 说明: 该组件从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。该组件的父组件只能是List。 使用说明 当List…...

Docker:常用命令

文章目录 docker作用常用指令 docker 作用 Docker 是一种容器化平台,可以让开发者打包应用程序及其依赖项,并以容器的形式进行发布、交付和运行。 Docker 的一些主要作用: 应用程序隔离:Docker 使用容器技术,将应用程…...

如何搭建“Docker Registry私有仓库,在CentOS7”?

1、下载镜像Docker Registry docker pull registry:2.7.1 2、运行私有库Registry docker run -d -p 5000:5000 -v ${PWD}/registry:/var/lib/registry --restartalways --name registry registry:2.7.1 3、拉取镜像 docker pull busybox 4、打标签,修改IP&#x…...

DBA面试题:MySQL缓存池LRU算法做了哪些改进?

下图是MySQL(MySQL5.7版本)体系架构图 MySQL的InnoDb Buffer Pool 缓冲池是主内存中的一个区域,用来缓存InnoDB在访问表和索引时的数据。对于频繁使用的数据可以直接从内存中访问,从而加快处理速度。如果一台服务器专用作MySQL数据…...

idea+vim+pycharm的块选择快捷键

平时开发的时候,有的时候我们想用矩形框住代码,或者想在某列上插入相同字符 例如下图所示,我想在22-24行的前面插入0000 1. Idea的快捷键:option 鼠标 2. Pycharm的快捷键:shift option 鼠标 2. Vim 块选择 v/V/c…...

ansible 部署FATE集群单边场景

官方文档: https://github.com/FederatedAI/AnsibleFATE/blob/main/docs/ansible_deploy_FATE_manual.md https://github.com/FederatedAI/AnsibleFATE/blob/main/docs/ansible_deploy_two_sides.md gitee详细文档: docs/ansible_deploy_one_side.md…...

融入Facebook的世界:探索数字化社交的魅力

融入Facebook的世界,是一场数字化社交的奇妙之旅。在这个广袤的虚拟社交空间中,人们可以尽情展现自己、分享生活,与全球朋友、家人和同事保持紧密联系,共同探索社交互动的乐趣与魅力。让我们深入了解这个世界的魅力所在&#xff1…...

stm32-定时器输出比较PWM

目录 一、输出比较简介 二、PWM简介 三、输出比较模式实现 1.输出比较框图(以通用定时器为例) 2.PWM基本结构 四、固件库实现 1.程序1:PWM呼吸灯 2.程序2:PWM驱动直流电机 3.程序3:控制舵机 一、输出比较简介 死区生成和互补输出一般…...

Redis对过期key的删除策略

假设设置了一批 key 只能存活 1 个小时,那么 1 小时后,redis 是怎么对这批 key 进行删除的? 定期删除 惰性删除 定期删除: redis是默认每隔100ms就随机抽取一些设置了过期时间的key,检查是否过期,如果过期就删除。…...

http的body格式

body数据都通常放在 HTTP 请求的 body 部分。 在 HTTP 请求中,Content-Type 头用于指示 body 中的数据格式。例如,对于 x-www-form-urlencoded 格式的数据,通常会设置 Content-Type: application/x-www-form-urlencoded,而对于 fo…...

Java Web开发从0到1

文章目录 总纲第1章 Java Web应用开发概述1.1 程序开发体系结构1.1.1 C/S体系结构介绍1.1.2 B/S体系结构介绍1.1.3 两种体系结构的比较1.2 Web应用程序的工作原理1.3 Web应用技术1.3.1 客服端应用技术1.3.2 服务端应用技术1.4 Java Web应用的开发环境变量1.5 Tomcat的安装与配置…...

002——编译鸿蒙(Liteos -a)

目录 一、鸿蒙是什么 二、Kconfig 2.1 概述 2.2 编译器 2.3 make使用 本文章引用了很多韦东山老师的教程内容,算是我学习过程中的笔记吧。如果侵权请联系我。 一、鸿蒙是什么 这里我补充一下对鸿蒙的描述 这张图片是鸿蒙发布时使用的,鸿蒙是一个很…...

Ansible--详解

目录 一、Ansible核心组件 二、Ansible配置 1.配置案例 (1)管理安装ansible (2)管理机分发公匙 (3)配置管理 (4)测试连接 2.命令说明 三、playbook剧本编写 1.playbook模板…...

Django和Mysql数据库

Django学习笔记 Django和Mysql数据库 Django开发操作数据库更简单,内部提供了ORM框架。 1)安装mysqlclient pip3 install mysqlclient2)ORM ORM可以帮助我们做两件事: 1.创建、修改、修改数据库中的表(不用写sql语句)[不能创…...

[蓝桥杯]-最大的通过数-CPP-二分查找、前缀和

目录 一、题目描述: 二、整体思路: 三、代码: 一、题目描述: 二、整体思路: 首先要知道不是他们同时选择序号一样的关卡通关,而是两人同时进行两个入口闯关。就是说两条通道存在相同关卡编号的的关卡被通…...

安卓UI面试题 26-30

26. Window和DecorView是什么?DecorView又是如何和Window建立联系的?Window是 WindowManager 最顶层的视图,它负责背景(窗口背景)、Title之类的标准的UI元素, Window是一个抽 象类,整个Android系统中, PhoneWindow是 Window的唯一实现类。 至于 DecorView,它是一个顶级 …...

CPU、GPU、IPU、NPU、TPU、LPU、MCU、MPU、SOC、DSP、FPGA、ASIC、GPP、ECU、

CPU: 中央处理器(Central Processing Unit)是一块超大规模的集成电路,是一台计算机的运算核心(Core)和控制核心( Control Unit)。 它的功能主要是解释计算机指令以及处理计算机软件…...

鸿蒙车载原生开发,拓展新版图

一天内连发“五弹”、HiCar 4.0首次上车 华为鸿蒙狂扩“汽车朋友圈”-上游新闻 汇聚向上的力量 3月15日,在“华为云&华为终端云服务创新峰会2024”上,华为首批汽车行业伙伴广汽传祺、岚图汽车、零跑汽车、凯翼汽车加入鸿蒙生态合作,华为…...

15届蓝桥杯第二期模拟赛题单详细解析

文章目录 🧡🧡t1_求余🧡🧡思路代码 🧡🧡t2_灌水🧡🧡思路代码 🧡🧡t3_字符显示🧡🧡思路代码 🧡🧡t4_区间最大和…...

mysql统计数据库大小

ps:亲测可行,时间2024-03-15 15:18 mysql统计数据库大小 要统计MySQL数据库的大小,你可以使用以下SQL查询: SELECT table_schema AS "Database",ROUND(SUM(data_length index_length) / 1024 / 1024, 2) AS "Size (MB)"FROM info…...

centos防火墙firewall-cmd限定特定的ip访问

文章目录 firewall-cmd是什么?启动firewalld服务查看默认区域关闭端口访问添加富规则firewall-cmd的区域概念firewall-cmd的常用选项通用选项:状态选项:永久选项:区域选项: firewall-cmd是什么? firewall-…...

创维汽车与创维光伏储能亮相2024上海AWE,感受制造业的升级变迁

2024年3月14日,中国家电及电子消费博览会在上海正式召开。相比往届展会,2024上海AWE进驻更多行业头部力量,出展更多尖端科技,蕴含更深行业思考。创维光伏储能及乘载更先进智驾科技的创维汽车亮相此次展会。 消费电子的革新不断影响…...

Kafka配置SASL_PLAINTEXT权限。常用操作命令,创建用户,topic授权

查看已经创建的topic ./bin/kafka-topics.sh --bootstrap-server localhost:9092 --list 创建topic 创建分区和副本数为1的topic ./bin/kafka-topics.sh --create --bootstrap-server localhost:9092 --topic acltest --partitions 1 --replication-factor 1 创建kafka用户 …...

[Java、Android面试]_05_内存泄漏和内存溢出

本人今年参加了很多面试,也有幸拿到了一些大厂的offer,整理了众多面试资料,后续还会分享众多面试资料。 整理成了面试系列,由于时间有限,每天整理一点,后续会陆续分享出来,感兴趣的朋友可关注收…...

MySQL-HMA 高可用故障切换

本章内容: 了解MySQL MHA搭建MySQL MHAMySQL MHA故障切换 1.案例分析 1.1.1案例概述 目前 MySQL 已经成为市场上主流数据库之一,考虑到业务的重要性,MySQL 数据库 单点问题已成为企业网站架构中最大的隐患。随着技术的发展,MHA…...

深度学习 精选笔记(11)深度学习计算相关:GPU、参数、读写、块

学习参考: 动手学深度学习2.0Deep-Learning-with-TensorFlow-bookpytorchlightning ①如有冒犯、请联系侵删。 ②已写完的笔记文章会不定时一直修订修改(删、改、增),以达到集多方教程的精华于一文的目的。 ③非常推荐上面(学习参考&#x…...