当前位置: 首页 > 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,它是一个顶级 …...

网络编程(Modbus进阶)

思维导图 Modbus RTU(先学一点理论) 概念 Modbus RTU 是工业自动化领域 最广泛应用的串行通信协议,由 Modicon 公司(现施耐德电气)于 1979 年推出。它以 高效率、强健性、易实现的特点成为工业控制系统的通信标准。 包…...

【网络】每天掌握一个Linux命令 - iftop

在Linux系统中,iftop是网络管理的得力助手,能实时监控网络流量、连接情况等,帮助排查网络异常。接下来从多方面详细介绍它。 目录 【网络】每天掌握一个Linux命令 - iftop工具概述安装方式核心功能基础用法进阶操作实战案例面试题场景生产场景…...

Xshell远程连接Kali(默认 | 私钥)Note版

前言:xshell远程连接,私钥连接和常规默认连接 任务一 开启ssh服务 service ssh status //查看ssh服务状态 service ssh start //开启ssh服务 update-rc.d ssh enable //开启自启动ssh服务 任务二 修改配置文件 vi /etc/ssh/ssh_config //第一…...

盘古信息PCB行业解决方案:以全域场景重构,激活智造新未来

一、破局:PCB行业的时代之问 在数字经济蓬勃发展的浪潮中,PCB(印制电路板)作为 “电子产品之母”,其重要性愈发凸显。随着 5G、人工智能等新兴技术的加速渗透,PCB行业面临着前所未有的挑战与机遇。产品迭代…...

Python如何给视频添加音频和字幕

在Python中,给视频添加音频和字幕可以使用电影文件处理库MoviePy和字幕处理库Subtitles。下面将详细介绍如何使用这些库来实现视频的音频和字幕添加,包括必要的代码示例和详细解释。 环境准备 在开始之前,需要安装以下Python库:…...

汇编常见指令

汇编常见指令 一、数据传送指令 指令功能示例说明MOV数据传送MOV EAX, 10将立即数 10 送入 EAXMOV [EBX], EAX将 EAX 值存入 EBX 指向的内存LEA加载有效地址LEA EAX, [EBX4]将 EBX4 的地址存入 EAX(不访问内存)XCHG交换数据XCHG EAX, EBX交换 EAX 和 EB…...

智能仓储的未来:自动化、AI与数据分析如何重塑物流中心

当仓库学会“思考”,物流的终极形态正在诞生 想象这样的场景: 凌晨3点,某物流中心灯火通明却空无一人。AGV机器人集群根据实时订单动态规划路径;AI视觉系统在0.1秒内扫描包裹信息;数字孪生平台正模拟次日峰值流量压力…...

算法岗面试经验分享-大模型篇

文章目录 A 基础语言模型A.1 TransformerA.2 Bert B 大语言模型结构B.1 GPTB.2 LLamaB.3 ChatGLMB.4 Qwen C 大语言模型微调C.1 Fine-tuningC.2 Adapter-tuningC.3 Prefix-tuningC.4 P-tuningC.5 LoRA A 基础语言模型 A.1 Transformer (1)资源 论文&a…...

网站指纹识别

网站指纹识别 网站的最基本组成:服务器(操作系统)、中间件(web容器)、脚本语言、数据厍 为什么要了解这些?举个例子:发现了一个文件读取漏洞,我们需要读/etc/passwd,如…...

视觉slam十四讲实践部分记录——ch2、ch3

ch2 一、使用g++编译.cpp为可执行文件并运行(P30) g++ helloSLAM.cpp ./a.out运行 二、使用cmake编译 mkdir build cd build cmake .. makeCMakeCache.txt 文件仍然指向旧的目录。这表明在源代码目录中可能还存在旧的 CMakeCache.txt 文件,或者在构建过程中仍然引用了旧的路…...