10.5 AlarmManager(闹钟服务)
核对 Android AlarmManager 与 Timer 的 CPU 休眠差异、全部调度方法与五种闹钟类型(时钟基准匹配)、PendingIntent 绑定要点、闹钟示例 Calendar.HOUR 纠偏,以及 Doze 模式与 Android 12+ SCHEDULE_EXACT_ALARM 精确闹钟限制。
学完这一章,你能够
- 核对 Android AlarmManager 与 Timer 的 CPU 休眠差异、全部调度方法与五种闹钟类型(时钟基准匹配)、PendingIntent 绑定要点、闹钟示例 Calendar.HOUR 纠偏,以及 Doze 模式与 Android 12+ SCHEDULE_EXACT_ALARM 精确闹钟限制。
AlarmManager 定位、Timer 对比与方法/参数体系
`AlarmManager` 是 Android 系统级定时唤醒服务,可在预设时刻通过系统广播触发指定的 `PendingIntent`(即使应用进程当时未在运行)。与 Java 标准库 `Timer` 相比,`Timer` 在设备长时间无操作、CPU 进入深度休眠后会被冻结而无法准时执行;`AlarmManager` 的 `*_WAKEUP` 类型则具备唤醒 CPU 的能力。同时需牢记:已注册的闹钟在设备关机或重启后会被清空,如需持久化须监听 `ACTION_BOOT_COMPLETED` 广播重新注册。自 API 19(Android 4.4)起,`set()` 与 `setRepeating()` 为省电改为非精确批处理触发,需要高精度时应改用 `setWindow()` 或 `setExact()`。
`AlarmManager` 的核心方法涵盖一次性/重复调度(`set`、`setExact`、`setWindow`、`setRepeating`、`setInexactRepeating`)、低电 Doze 穿透调度(`setAndAllowWhileIdle`、`setExactAndAllowWhileIdle`、`setAlarmClock`)、取消与查询(`cancel(PendingIntent)`、`getNextAlarmClock()`)以及系统时间设置(`setTime`、`setTimeZone`,需系统权限)。四项关键参数务必严格配对:① **闹钟类型(`type`)**:标准四种为 `RTC_WAKEUP(0)`(墙钟绝对时间、休眠可唤醒)、`RTC(1)`(墙钟绝对时间、不唤醒)、`ELAPSED_REALTIME_WAKEUP(2)`(相对开机时间、休眠可唤醒)与 `ELAPSED_REALTIME(3)`(相对开机时间、不唤醒),另有部分早期厂商私有扩展 `POWER_OFF_WAKEUP(4)` 并非标准公开 SDK 保证能力;② **`startTime` 必须与 `type` 时钟基准一致**:`ELAPSED_REALTIME*` 须基于 `SystemClock.elapsedRealtime()`,`RTC*` 须基于 `System.currentTimeMillis()`,混用会导致立即误触发或永不触发;③ `intervalTime` 为重复间隔毫秒数;④ `PendingIntent` 工厂方法必须与目标组件严格对应(`getActivity`、`getService`、`getBroadcast`,错用不会抛异常但组件不会响应,且 API 31+ 须显式声明 `FLAG_IMMUTABLE`/`FLAG_MUTABLE`)。
定时闹钟实战纠偏、Doze 休眠与 Android 12+ 精确闹钟演进
闹钟示例的完整流程为:获取 `AlarmManager` -> 构造指向 `ClockActivity` 的 `Intent` 与 `PendingIntent.getActivity(...)` -> 通过 `TimePickerDialog` 选取时分后调用 `alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi)`,到点启动 `ClockActivity` 播放 `R.raw.pig` 并弹出 `AlertDialog` 供关闭铃声(结合后台 `Service` 轮询可参见 `4.2.2 Service进阶`)。针对示例中的常见坑点与现代系统适配需做四点关键纠偏:① 原文提示精确方法时误写作 `setExtra()`,实际方法名为 `setExact()`;② `MainActivity` 写入 `c.set(Calendar.HOUR, hourOfDay)` 在 24 小时制下午时段存在 AM/PM 偏差,应改为 `Calendar.HOUR_OF_DAY`,并把 `SECOND`/`MILLISECOND` 清零、若所选时间已早于当前时刻则加 1 天顺延至次日;③ 从 `BroadcastReceiver` 启动 `Activity` 必须添加 `Intent.FLAG_ACTIVITY_NEW_TASK` 且在清单注册 `ClockActivity`;④ **现代 Android(API 23/29/31/33+)演进**:Android 6.0 起引入 Doze 模式会推迟普通/精确闹钟,须用 `setExactAndAllowWhileIdle()` 或 `setAlarmClock()`;Android 10(API 29)起严格限制后台直接拉起 `Activity`,闹钟界面应通过高优先级 `Notification` 的 `setFullScreenIntent()` 展示;Android 12(API 31)起调用精确闹钟须声明 `SCHEDULE_EXACT_ALARM` 并通过 `canScheduleExactAlarms()` 检查授权(Android 13+ 专用闹钟/日历类应用可声明 `USE_EXACT_ALARM`,常规非精确后台周期任务则应改用 Jetpack `WorkManager`)。来源页面附带的 `AlarmManagerDemo.zip` 因继承停采策略未联网下载,已单独登记留痕。
运行离线 AlarmManager 类型时钟基准、Doze/SCHEDULE_EXACT_ALARM 校验与 24h 顺延核验
"""Offline Android system-service verifier for Ch 140: AlarmManager, Doze & Exact Alarms."""
from dataclasses import dataclass
import json
import xml.etree.ElementTree as ET
VERSION = "CPython 3.12.14 offline Android graphics/animation/media/service verifier (Android SDK/emulator absent)"
ALARM_LAYOUT_XML = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button android:id="@+id/btn_set" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="设置闹钟" />
<Button android:id="@+id/btn_cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="关闭闹钟" android:visibility="gone" />
</LinearLayout>
"""
ALARM_TYPES = {
"RTC_WAKEUP": (0, "wall_clock", True),
"RTC": (1, "wall_clock", False),
"ELAPSED_REALTIME_WAKEUP": (2, "elapsed_boot", True),
"ELAPSED_REALTIME": (3, "elapsed_boot", False),
}
@dataclass
class AlarmJob:
alarm_type: str
trigger_ms: int
delivery_mode: str # "inexact", "window", "exact", "exact_allow_while_idle", "alarm_clock"
target_component: str # "activity", "service", "broadcast"
def validate_alarm(job: AlarmJob, clock_source: str, api_level: int, has_exact_perm: bool, in_doze: bool) -> dict:
_, expected_clock, wakes_cpu = ALARM_TYPES[job.alarm_type]
clock_match = (clock_source == expected_clock)
exact_modes = ("exact", "exact_allow_while_idle", "alarm_clock")
needs_exact_perm = api_level >= 31 and job.delivery_mode in ("exact", "exact_allow_while_idle")
allowed = (not needs_exact_perm) or has_exact_perm
fires_in_doze = (not in_doze) or (job.delivery_mode in ("exact_allow_while_idle", "alarm_clock"))
bg_activity_blocked = api_level >= 29 and job.target_component == "activity"
return {
"clock_match": clock_match,
"wakes_cpu": wakes_cpu,
"permission_allowed": allowed,
"fires_during_doze": fires_in_doze,
"bg_activity_restricted": bg_activity_blocked,
}
def main() -> None:
# Case 1: 4 standard AlarmManager types, numeric constants & matching clock source (RTC vs ELAPSED_REALTIME)
c1_actual = {
name: {"code": code, "clock": clk, "wakes": wake}
for name, (code, clk, wake) in ALARM_TYPES.items()
}
c1_expected = {
"RTC_WAKEUP": {"code": 0, "clock": "wall_clock", "wakes": True},
"RTC": {"code": 1, "clock": "wall_clock", "wakes": False},
"ELAPSED_REALTIME_WAKEUP": {"code": 2, "clock": "elapsed_boot", "wakes": True},
"ELAPSED_REALTIME": {"code": 3, "clock": "elapsed_boot", "wakes": False},
}
# Case 2: Doze mode (API 23+) & Android 12+ (API 31) SCHEDULE_EXACT_ALARM enforcement
j_exact_no_perm = AlarmJob("ELAPSED_REALTIME_WAKEUP", 60000, "exact", "broadcast")
j_idle_with_perm = AlarmJob("RTC_WAKEUP", 1700000060000, "exact_allow_while_idle", "broadcast")
j_wrong_clock = AlarmJob("ELAPSED_REALTIME_WAKEUP", 1700000060000, "inexact", "broadcast")
c2_actual = {
"api31_exact_without_perm": validate_alarm(j_exact_no_perm, "elapsed_boot", 31, False, True),
"api31_exact_allow_idle_with_perm": validate_alarm(j_idle_with_perm, "wall_clock", 31, True, True),
"elapsed_type_with_wall_clock_mismatch": validate_alarm(j_wrong_clock, "wall_clock", 31, False, False)["clock_match"],
}
c2_expected = {
"api31_exact_without_perm": {
"clock_match": True,
"wakes_cpu": True,
"permission_allowed": False,
"fires_during_doze": False,
"bg_activity_restricted": False,
},
"api31_exact_allow_idle_with_perm": {
"clock_match": True,
"wakes_cpu": True,
"permission_allowed": True,
"fires_during_doze": True,
"bg_activity_restricted": False,
},
"elapsed_type_with_wall_clock_mismatch": False,
}
# Case 3: Demo TimePicker Calendar.HOUR vs Calendar.HOUR_OF_DAY bug & next-day rollover
# At 14:00 (2 PM), user picks 15:30: Calendar.HOUR sets 12h offset (AM/PM issue if 15 >= 12),
# whereas HOUR_OF_DAY sets exact 15:30; if user picks 08:00 at 14:00, must roll +1 day!
now_min = 14 * 60
pick_future = 15 * 60 + 30
pick_past = 8 * 60
rollover_future_days = 0 if pick_future > now_min else 1
rollover_past_days = 0 if pick_past > now_min else 1
root = ET.fromstring(ALARM_LAYOUT_XML)
c3_actual = {
"layout_buttons": len(root.findall("Button")),
"use_hour_of_day_for_24h": True,
"rollover_days_15_30_at_14_00": rollover_future_days,
"rollover_days_08_00_at_14_00": rollover_past_days,
}
c3_expected = {
"layout_buttons": 2,
"use_hour_of_day_for_24h": True,
"rollover_days_15_30_at_14_00": 0,
"rollover_days_08_00_at_14_00": 1,
}
# Case 4: PendingIntent component matching & API 29+ background Activity launch restriction
j_legacy_act = AlarmJob("RTC_WAKEUP", 1700000060000, "alarm_clock", "activity")
c4_actual = {
"pending_intent_factories": {
"activity": "PendingIntent.getActivity",
"service": "PendingIntent.getService",
"broadcast": "PendingIntent.getBroadcast",
},
"bg_activity_restricted_api29": validate_alarm(j_legacy_act, "wall_clock", 31, True, True)["bg_activity_restricted"],
"broadcast_to_activity_flag": "Intent.FLAG_ACTIVITY_NEW_TASK",
"survives_reboot_without_boot_receiver": False,
}
c4_expected = {
"pending_intent_factories": {
"activity": "PendingIntent.getActivity",
"service": "PendingIntent.getService",
"broadcast": "PendingIntent.getBroadcast",
},
"bg_activity_restricted_api29": True,
"broadcast_to_activity_flag": "Intent.FLAG_ACTIVITY_NEW_TASK",
"survives_reboot_without_boot_receiver": False,
}
cases = [
{
"name": "alarmmanager_types_and_clock_bases",
"summary": "核验 AlarmManager 四种标准类型常量值、唤醒能力及墙钟/开机相对时间基准匹配",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "alarmmanager_doze_and_exact_alarm_permission",
"summary": "核验 Doze 休眠模式延迟行为、Android 12+ SCHEDULE_EXACT_ALARM 权限校验与时钟错配检测",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "alarm_timepicker_hour_of_day_and_rollover",
"summary": "核验闹钟示例布局、Calendar.HOUR_OF_DAY 24 小时制纠偏及过去时刻自动顺延次日逻辑",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
{
"name": "pending_intent_component_match_and_reboot",
"summary": "核验 PendingIntent 三类工厂方法匹配、API 29+ 后台启动 Activity 限制及重启清除特性",
"expected": c4_expected,
"actual": c4_actual,
"passed": c4_actual == c4_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 验证四类标准常量与时钟基准、API 31 精确闹钟权限与 Doze 穿透判定、HOUR_OF_DAY 顺延及 PendingIntent 限制。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:e41bea5e3789974e8dc61b1ef39eca6218b94f14beb0f3a0651a8fd0ab3143cc
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:1b2d91390f285dfb8fecefefd21bf6e57939bb531e53673ce48d851f441ba694
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Android 12(API 31)及更高版本中使用 `AlarmManager.setExactAndAllowWhileIdle()` 调度精确闹钟前,除了匹配 `ELAPSED_REALTIME_WAKEUP` 与 `SystemClock.elapsedRealtime()`,还必须满足什么系统权限与兼容要求?
展开参考解答
必须在清单中声明 `android.permission.SCHEDULE_EXACT_ALARM`(Android 13+ 专用闹钟/日历类应用可使用 `USE_EXACT_ALARM`),并在调度前调用 `alarmManager.canScheduleExactAlarms()` 确认已获用户授权,否则会抛出 `SecurityException`。