安卓如何每次重启开机后只执行一次代码

本文最后更新于:2025年11月9日 晚上

安卓如何每次重启开机后只执行一次代码:

方法一、开机广播

比较普遍的一个方法,但可能接收延迟或者被禁止接收。

方法二、设置一个非 persist 属性作为标记,重启后系统自动清除

受 selinux 管控,第三方应用无权限执行。

方法三、使用/proc/sys/kernel/random/boot_id 作为标记

相当于内核准备的一张 「本次开机身份证」

  • 每次重启都会变化一次
  • 在同一次开机过程中是稳定不变的

非常适合作为标记

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
private const val TAG = "BootUtil"
private const val PREF = "boot_util_prefs"

fun current(context: Context): String {
kotlin.runCatching {
val text = File("/proc/sys/kernel/random/boot_id").readText().trim()
if (text.isNotEmpty()) return text
}
kotlin.runCatching {
val cnt = Settings.Global.getInt(context.contentResolver, Settings.Global.BOOT_COUNT)
return "boot_count_$cnt"
}
return "unknown_boot"
}

fun runOnce(context: Context, block: () -> Unit) {
val marker = current(context).also {
Log.d(TAG, "current boot marker: $it")
}
val prefs = context.getSharedPreferences(PREF, Context.MODE_PRIVATE)
val doneKey = "boot_once_$marker"
val done = prefs.getBoolean(doneKey, false)
if (!done) {
block()
prefs.edit {
clear()
putBoolean(doneKey, true)
}
}
}

安卓如何每次重启开机后只执行一次代码
https://iwesley.top/article/ae07f8e0/
作者
Wesley
发布于
2025年11月9日
许可协议