"""Offline Android system-service verifier for Ch 141: PowerManager & WakeLock."""
from dataclasses import dataclass, field
import json
import xml.etree.ElementTree as ET
VERSION = (
"CPython 3.12.14 offline Android system-service/sensor/capstone verifier "
"(Android SDK/emulator absent)"
)
PARTIAL_WAKE_LOCK = 0x00000001
SCREEN_DIM_WAKE_LOCK = 0x00000006
SCREEN_BRIGHT_WAKE_LOCK = 0x0000000A
FULL_WAKE_LOCK = 0x0000001A
WAKE_LOCK_LEVEL_MASK = 0x0000FFFF
ACQUIRE_CAUSES_WAKEUP = 0x10000000
ON_AFTER_RELEASE = 0x20000000
VALID_LEVELS = {
PARTIAL_WAKE_LOCK: "PARTIAL_WAKE_LOCK",
SCREEN_DIM_WAKE_LOCK: "SCREEN_DIM_WAKE_LOCK",
SCREEN_BRIGHT_WAKE_LOCK: "SCREEN_BRIGHT_WAKE_LOCK",
FULL_WAKE_LOCK: "FULL_WAKE_LOCK",
}
DEPRECATED_SCREEN_LEVELS = {
SCREEN_DIM_WAKE_LOCK,
SCREEN_BRIGHT_WAKE_LOCK,
FULL_WAKE_LOCK,
}
@dataclass
class WakeLockModel:
flags: int
tag: str
reference_counted: bool = True
count: int = 0
held: bool = False
kernel_acquires: int = 0
kernel_releases: int = 0
expires_at_ms: int | None = None
screen_woken: bool = False
after_release_reset: bool = False
history: list[str] = field(default_factory=list)
def __post_init__(self) -> None:
level = self.flags & WAKE_LOCK_LEVEL_MASK
if level not in VALID_LEVELS:
raise ValueError(f"Invalid exclusive WakeLock level: {hex(level)}")
self.level = level
self.causes_wakeup = bool(self.flags & ACQUIRE_CAUSES_WAKEUP)
self.on_after_release = bool(self.flags & ON_AFTER_RELEASE)
def set_reference_counted(self, value: bool) -> None:
self.reference_counted = value
def acquire(self, now_ms: int = 0, timeout_ms: int | None = None) -> None:
if self.reference_counted:
if self.count == 0:
self.held = True
self.kernel_acquires += 1
self.count += 1
else:
if not self.held:
self.held = True
self.kernel_acquires += 1
self.count = 1
if timeout_ms is not None:
self.expires_at_ms = now_ms + timeout_ms
if self.causes_wakeup and self.level != PARTIAL_WAKE_LOCK:
self.screen_woken = True
self.history.append(f"acquire(count={self.count},held={self.held})")
def release(self) -> None:
if self.reference_counted:
if self.count <= 0:
raise RuntimeError(f"WakeLock under-locked: {self.tag}")
self.count -= 1
if self.count == 0:
self.held = False
self.kernel_releases += 1
self.expires_at_ms = None
if self.on_after_release and self.level != PARTIAL_WAKE_LOCK:
self.after_release_reset = True
else:
if self.held:
self.held = False
self.count = 0
self.kernel_releases += 1
self.expires_at_ms = None
if self.on_after_release and self.level != PARTIAL_WAKE_LOCK:
self.after_release_reset = True
self.history.append(f"release(count={self.count},held={self.held})")
def advance_time(self, now_ms: int) -> None:
if self.held and self.expires_at_ms is not None and now_ms >= self.expires_at_ms:
self.held = False
self.count = 0
self.kernel_releases += 1
self.expires_at_ms = None
self.history.append(f"timeout_release(t={now_ms})")
def main() -> None:
# Case 1: Reference-counted vs non-reference-counted WakeLock + release-in-finally
wl_ref = WakeLockModel(SCREEN_DIM_WAKE_LOCK, "MyApp:SyncTag", reference_counted=True)
wl_ref.acquire()
wl_ref.acquire()
after_two_acquires = (wl_ref.count, wl_ref.held, wl_ref.kernel_acquires)
wl_ref.release()
after_one_release = (wl_ref.count, wl_ref.held, wl_ref.kernel_releases)
wl_ref.release()
after_two_releases = (wl_ref.count, wl_ref.held, wl_ref.kernel_releases)
wl_nonref = WakeLockModel(PARTIAL_WAKE_LOCK, "MyApp:BgTag", reference_counted=False)
wl_nonref.acquire()
wl_nonref.acquire()
wl_nonref.release()
wl_finally = WakeLockModel(PARTIAL_WAKE_LOCK, "MyApp:SafeTask", reference_counted=True)
caught_error = False
try:
wl_finally.acquire(now_ms=1000, timeout_ms=10_000)
raise ValueError("simulated work failure")
except ValueError:
caught_error = True
finally:
if wl_finally.held:
wl_finally.release()
wl_timeout = WakeLockModel(PARTIAL_WAKE_LOCK, "MyApp:TimedTask")
wl_timeout.acquire(now_ms=0, timeout_ms=5000)
held_before = wl_timeout.held
wl_timeout.advance_time(5000)
held_after = wl_timeout.held
c1_actual = {
"ref_counted_two_acquires": list(after_two_acquires),
"ref_counted_after_first_release": list(after_one_release),
"ref_counted_after_second_release": list(after_two_releases),
"non_ref_counted_held_after_single_release": wl_nonref.held,
"finally_caught_and_released": caught_error and (not wl_finally.held),
"timeout_auto_release": [held_before, held_after],
}
c1_expected = {
"ref_counted_two_acquires": [2, True, 1],
"ref_counted_after_first_release": [1, True, 0],
"ref_counted_after_second_release": [0, False, 1],
"non_ref_counted_held_after_single_release": False,
"finally_caught_and_released": True,
"timeout_auto_release": [True, False],
}
# Case 2: Exclusive level flags + modifier flags (ACQUIRE_CAUSES_WAKEUP / ON_AFTER_RELEASE)
wl_partial_mod = WakeLockModel(PARTIAL_WAKE_LOCK | ACQUIRE_CAUSES_WAKEUP | ON_AFTER_RELEASE, "MyApp:Partial")
wl_partial_mod.acquire()
wl_partial_mod.release()
wl_bright_mod = WakeLockModel(SCREEN_BRIGHT_WAKE_LOCK | ACQUIRE_CAUSES_WAKEUP | ON_AFTER_RELEASE, "MyApp:Bright")
wl_bright_mod.acquire()
wl_bright_mod.release()
invalid_combined_rejected = False
try:
WakeLockModel(PARTIAL_WAKE_LOCK | FULL_WAKE_LOCK, "MyApp:Invalid")
except ValueError:
invalid_combined_rejected = True
c2_actual = {
"exclusive_level_count": len(VALID_LEVELS),
"deprecated_screen_levels": sorted(VALID_LEVELS[lvl] for lvl in DEPRECATED_SCREEN_LEVELS),
"partial_ignores_screen_modifiers": [wl_partial_mod.screen_woken, wl_partial_mod.after_release_reset],
"screen_lock_applies_modifiers": [wl_bright_mod.screen_woken, wl_bright_mod.after_release_reset],
"invalid_multi_level_rejected": invalid_combined_rejected,
}
c2_expected = {
"exclusive_level_count": 4,
"deprecated_screen_levels": ["FULL_WAKE_LOCK", "SCREEN_BRIGHT_WAKE_LOCK", "SCREEN_DIM_WAKE_LOCK"],
"partial_ignores_screen_modifiers": [False, False],
"screen_lock_applies_modifiers": [True, True],
"invalid_multi_level_rejected": True,
}
# Case 3: Manifest permissions audit (WAKE_LOCK vs privileged DEVICE_POWER)
manifest_xml = """<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.DEVICE_POWER"/>
</manifest>"""
root = ET.fromstring(manifest_xml)
ns = "{http://schemas.android.com/apk/res/android}"
perms = [el.attrib[f"{ns}name"] for el in root.findall("uses-permission")]
permission_tier = {
"android.permission.WAKE_LOCK": "normal_third_party_allowed",
"android.permission.DEVICE_POWER": "signature_or_privileged_only",
}
c3_actual = {
"declared_permissions": perms,
"tiers": [permission_tier[p] for p in perms],
"keep_screen_on_needs_wake_lock_perm": False,
}
c3_expected = {
"declared_permissions": [
"android.permission.WAKE_LOCK",
"android.permission.DEVICE_POWER",
],
"tiers": [
"normal_third_party_allowed",
"signature_or_privileged_only",
],
"keep_screen_on_needs_wake_lock_perm": False,
}
cases = [
{
"name": "wakelock_refcount_timeout_and_finally",
"summary": "验证 WakeLock 计数锁/不计数锁、超时自动释放及 try-finally 异常兜底释放机制",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "wakelock_level_flags_and_modifiers",
"summary": "验证 4 种独占唤醒级别标志、API 17 废弃范围及 ACQUIRE_CAUSES_WAKEUP/ON_AFTER_RELEASE 交互规则",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "powermanager_manifest_permissions",
"summary": "解析 AndroidManifest 电源权限声明并区分普通权限 WAKE_LOCK 与系统签名权限 DEVICE_POWER",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/android-tutorial-powermanager-lab/explore-tutorial-powermanager.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-powermanager.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1927.zip