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,它是一个顶级 …...
OpenLayers 可视化之热力图
注:当前使用的是 ol 5.3.0 版本,天地图使用的key请到天地图官网申请,并替换为自己的key 热力图(Heatmap)又叫热点图,是一种通过特殊高亮显示事物密度分布、变化趋势的数据可视化技术。采用颜色的深浅来显示…...
ES6从入门到精通:前言
ES6简介 ES6(ECMAScript 2015)是JavaScript语言的重大更新,引入了许多新特性,包括语法糖、新数据类型、模块化支持等,显著提升了开发效率和代码可维护性。 核心知识点概览 变量声明 let 和 const 取代 var…...
docker详细操作--未完待续
docker介绍 docker官网: Docker:加速容器应用程序开发 harbor官网:Harbor - Harbor 中文 使用docker加速器: Docker镜像极速下载服务 - 毫秒镜像 是什么 Docker 是一种开源的容器化平台,用于将应用程序及其依赖项(如库、运行时环…...
python如何将word的doc另存为docx
将 DOCX 文件另存为 DOCX 格式(Python 实现) 在 Python 中,你可以使用 python-docx 库来操作 Word 文档。不过需要注意的是,.doc 是旧的 Word 格式,而 .docx 是新的基于 XML 的格式。python-docx 只能处理 .docx 格式…...
ElasticSearch搜索引擎之倒排索引及其底层算法
文章目录 一、搜索引擎1、什么是搜索引擎?2、搜索引擎的分类3、常用的搜索引擎4、搜索引擎的特点二、倒排索引1、简介2、为什么倒排索引不用B+树1.创建时间长,文件大。2.其次,树深,IO次数可怕。3.索引可能会失效。4.精准度差。三. 倒排索引四、算法1、Term Index的算法2、 …...
3-11单元格区域边界定位(End属性)学习笔记
返回一个Range 对象,只读。该对象代表包含源区域的区域上端下端左端右端的最后一个单元格。等同于按键 End 向上键(End(xlUp))、End向下键(End(xlDown))、End向左键(End(xlToLeft)End向右键(End(xlToRight)) 注意:它移动的位置必须是相连的有内容的单元格…...
Angular微前端架构:Module Federation + ngx-build-plus (Webpack)
以下是一个完整的 Angular 微前端示例,其中使用的是 Module Federation 和 npx-build-plus 实现了主应用(Shell)与子应用(Remote)的集成。 🛠️ 项目结构 angular-mf/ ├── shell-app/ # 主应用&…...
虚拟电厂发展三大趋势:市场化、技术主导、车网互联
市场化:从政策驱动到多元盈利 政策全面赋能 2025年4月,国家发改委、能源局发布《关于加快推进虚拟电厂发展的指导意见》,首次明确虚拟电厂为“独立市场主体”,提出硬性目标:2027年全国调节能力≥2000万千瓦࿰…...
关于uniapp展示PDF的解决方案
在 UniApp 的 H5 环境中使用 pdf-vue3 组件可以实现完整的 PDF 预览功能。以下是详细实现步骤和注意事项: 一、安装依赖 安装 pdf-vue3 和 PDF.js 核心库: npm install pdf-vue3 pdfjs-dist二、基本使用示例 <template><view class"con…...
Django RBAC项目后端实战 - 03 DRF权限控制实现
项目背景 在上一篇文章中,我们完成了JWT认证系统的集成。本篇文章将实现基于Redis的RBAC权限控制系统,为系统提供细粒度的权限控制。 开发目标 实现基于Redis的权限缓存机制开发DRF权限控制类实现权限管理API配置权限白名单 前置配置 在开始开发权限…...
