蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行离线 AlarmManager 类型时钟基准、Doze/SCHEDULE_EXACT_ALARM 校验与 24h 顺延核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-alarmmanager.py
explore-tutorial-alarmmanager.py171 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/android-tutorial-alarmmanager-lab/explore-tutorial-alarmmanager.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-alarmmanager.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1836.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习