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的世界,是一场数字化社交的奇妙之旅。在这个广袤的虚拟社交空间中,人们可以尽情展现自己、分享生活,与全球朋友、家人和同事保持紧密联系,共同探索社交互动的乐趣与魅力。让我们深入了解这个世界的魅力所在࿱…...
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,它是一个顶级 …...
接口测试中缓存处理策略
在接口测试中,缓存处理策略是一个关键环节,直接影响测试结果的准确性和可靠性。合理的缓存处理策略能够确保测试环境的一致性,避免因缓存数据导致的测试偏差。以下是接口测试中常见的缓存处理策略及其详细说明: 一、缓存处理的核…...
C++实现分布式网络通信框架RPC(3)--rpc调用端
目录 一、前言 二、UserServiceRpc_Stub 三、 CallMethod方法的重写 头文件 实现 四、rpc调用端的调用 实现 五、 google::protobuf::RpcController *controller 头文件 实现 六、总结 一、前言 在前边的文章中,我们已经大致实现了rpc服务端的各项功能代…...
智慧医疗能源事业线深度画像分析(上)
引言 医疗行业作为现代社会的关键基础设施,其能源消耗与环境影响正日益受到关注。随着全球"双碳"目标的推进和可持续发展理念的深入,智慧医疗能源事业线应运而生,致力于通过创新技术与管理方案,重构医疗领域的能源使用模式。这一事业线融合了能源管理、可持续发…...
关于nvm与node.js
1 安装nvm 安装过程中手动修改 nvm的安装路径, 以及修改 通过nvm安装node后正在使用的node的存放目录【这句话可能难以理解,但接着往下看你就了然了】 2 修改nvm中settings.txt文件配置 nvm安装成功后,通常在该文件中会出现以下配置&…...
基于服务器使用 apt 安装、配置 Nginx
🧾 一、查看可安装的 Nginx 版本 首先,你可以运行以下命令查看可用版本: apt-cache madison nginx-core输出示例: nginx-core | 1.18.0-6ubuntu14.6 | http://archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages ng…...
电脑插入多块移动硬盘后经常出现卡顿和蓝屏
当电脑在插入多块移动硬盘后频繁出现卡顿和蓝屏问题时,可能涉及硬件资源冲突、驱动兼容性、供电不足或系统设置等多方面原因。以下是逐步排查和解决方案: 1. 检查电源供电问题 问题原因:多块移动硬盘同时运行可能导致USB接口供电不足&#x…...
SpringBoot+uniapp 的 Champion 俱乐部微信小程序设计与实现,论文初版实现
摘要 本论文旨在设计并实现基于 SpringBoot 和 uniapp 的 Champion 俱乐部微信小程序,以满足俱乐部线上活动推广、会员管理、社交互动等需求。通过 SpringBoot 搭建后端服务,提供稳定高效的数据处理与业务逻辑支持;利用 uniapp 实现跨平台前…...
k8s业务程序联调工具-KtConnect
概述 原理 工具作用是建立了一个从本地到集群的单向VPN,根据VPN原理,打通两个内网必然需要借助一个公共中继节点,ktconnect工具巧妙的利用k8s原生的portforward能力,简化了建立连接的过程,apiserver间接起到了中继节…...
SpringTask-03.入门案例
一.入门案例 启动类: package com.sky;import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCach…...
CSS设置元素的宽度根据其内容自动调整
width: fit-content 是 CSS 中的一个属性值,用于设置元素的宽度根据其内容自动调整,确保宽度刚好容纳内容而不会超出。 效果对比 默认情况(width: auto): 块级元素(如 <div>)会占满父容器…...
