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

深度学习在微纳光子学中的应用

深度学习在微纳光子学中的主要应用方向 深度学习与微纳光子学的结合主要集中在以下几个方向: 逆向设计 通过神经网络快速预测微纳结构的光学响应,替代传统耗时的数值模拟方法。例如设计超表面、光子晶体等结构。 特征提取与优化 从复杂的光学数据中自…...

docker详细操作--未完待续

docker介绍 docker官网: Docker:加速容器应用程序开发 harbor官网:Harbor - Harbor 中文 使用docker加速器: Docker镜像极速下载服务 - 毫秒镜像 是什么 Docker 是一种开源的容器化平台,用于将应用程序及其依赖项(如库、运行时环…...

《Playwright:微软的自动化测试工具详解》

Playwright 简介:声明内容来自网络,将内容拼接整理出来的文档 Playwright 是微软开发的自动化测试工具,支持 Chrome、Firefox、Safari 等主流浏览器,提供多语言 API(Python、JavaScript、Java、.NET)。它的特点包括&a…...

【磁盘】每天掌握一个Linux命令 - iostat

目录 【磁盘】每天掌握一个Linux命令 - iostat工具概述安装方式核心功能基础用法进阶操作实战案例面试题场景生产场景 注意事项 【磁盘】每天掌握一个Linux命令 - iostat 工具概述 iostat(I/O Statistics)是Linux系统下用于监视系统输入输出设备和CPU使…...

2021-03-15 iview一些问题

1.iview 在使用tree组件时,发现没有set类的方法,只有get,那么要改变tree值,只能遍历treeData,递归修改treeData的checked,发现无法更改,原因在于check模式下,子元素的勾选状态跟父节…...

视频字幕质量评估的大规模细粒度基准

大家读完觉得有帮助记得关注和点赞!!! 摘要 视频字幕在文本到视频生成任务中起着至关重要的作用,因为它们的质量直接影响所生成视频的语义连贯性和视觉保真度。尽管大型视觉-语言模型(VLMs)在字幕生成方面…...

Psychopy音频的使用

Psychopy音频的使用 本文主要解决以下问题: 指定音频引擎与设备;播放音频文件 本文所使用的环境: Python3.10 numpy2.2.6 psychopy2025.1.1 psychtoolbox3.0.19.14 一、音频配置 Psychopy文档链接为Sound - for audio playback — Psy…...

什么是EULA和DPA

文章目录 EULA(End User License Agreement)DPA(Data Protection Agreement)一、定义与背景二、核心内容三、法律效力与责任四、实际应用与意义 EULA(End User License Agreement) 定义: EULA即…...

使用 SymPy 进行向量和矩阵的高级操作

在科学计算和工程领域,向量和矩阵操作是解决问题的核心技能之一。Python 的 SymPy 库提供了强大的符号计算功能,能够高效地处理向量和矩阵的各种操作。本文将深入探讨如何使用 SymPy 进行向量和矩阵的创建、合并以及维度拓展等操作,并通过具体…...

初学 pytest 记录

安装 pip install pytest用例可以是函数也可以是类中的方法 def test_func():print()class TestAdd: # def __init__(self): 在 pytest 中不可以使用__init__方法 # self.cc 12345 pytest.mark.api def test_str(self):res add(1, 2)assert res 12def test_int(self):r…...