"""Offline Android system-service verifier for Ch 139: Vibrator & VibrationEffect (API 26+)."""
import json
import xml.etree.ElementTree as ET
VERSION = "CPython 3.12.14 offline Android graphics/animation/media/service verifier (Android SDK/emulator absent)"
VIBRATOR_LAYOUT_XML = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button android:id="@+id/btn_hasVibrator" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="判断是否有振动器" />
<Button android:id="@+id/btn_short" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="短振动" />
<Button android:id="@+id/btn_long" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="长振动" />
<Button android:id="@+id/btn_rhythm" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="节奏振动" />
<Button android:id="@+id/btn_cancle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="取消振动" />
</LinearLayout>
"""
def parse_waveform(pattern: list[int], repeat: int) -> dict:
if not pattern or any(v < 0 for v in pattern):
raise ValueError("Timings must be non-empty non-negative integers")
if repeat < -1 or repeat >= len(pattern):
raise ValueError("repeat must be -1 or a valid index into pattern")
segments = [
{"phase": "off" if i % 2 == 0 else "on", "ms": ms}
for i, ms in enumerate(pattern)
]
on_ms = sum(ms for i, ms in enumerate(pattern) if i % 2 == 1)
off_ms = sum(ms for i, ms in enumerate(pattern) if i % 2 == 0)
return {
"total_cycle_ms": on_ms + off_ms,
"on_ms": on_ms,
"off_ms": off_ms,
"duty_cycle": round(on_ms / (on_ms + off_ms), 4),
"repeats_forever": repeat >= 0,
"repeat_start_index": repeat,
"segment_count": len(segments),
}
def vibration_effect_oneshot(ms: int, amplitude: int = -1) -> dict:
# DEFAULT_AMPLITUDE == -1; explicit amplitudes in [1, 255]
if ms <= 0:
raise ValueError("Duration must be positive")
if amplitude != -1 and not (1 <= amplitude <= 255):
raise ValueError("Amplitude must be DEFAULT_AMPLITUDE (-1) or 1..255")
return {"type": "ONE_SHOT", "duration_ms": ms, "amplitude": amplitude}
def main() -> None:
# Case 1: Three demo vibration patterns (short, long, rhythm) duty-cycle & off/on alternation
short_p = parse_waveform([100, 200, 100, 200], 0)
long_p = parse_waveform([100, 100, 100, 1000], 0)
rhythm_p = parse_waveform([500, 100, 500, 100, 500, 100], 0)
c1_actual = {
"short": [short_p["total_cycle_ms"], short_p["on_ms"], short_p["duty_cycle"]],
"long": [long_p["total_cycle_ms"], long_p["on_ms"], long_p["duty_cycle"]],
"rhythm": [rhythm_p["total_cycle_ms"], rhythm_p["on_ms"], rhythm_p["duty_cycle"]],
}
c1_expected = {
"short": [600, 400, 0.6667],
"long": [1300, 1100, 0.8462],
"rhythm": [1800, 300, 0.1667],
}
# Case 2: repeat parameter semantics (-1 = play once; >=0 = loop starting from index, NOT repeat count!)
once_p = parse_waveform([200, 400, 600, 800], -1)
idx2_p = parse_waveform([200, 400, 600, 800], 2)
oob_rejected = False
try:
parse_waveform([200, 400], 2)
except ValueError:
oob_rejected = True
c2_actual = {
"repeat_minus1_loops": once_p["repeats_forever"],
"repeat_2_start_index": idx2_p["repeat_start_index"],
"repeat_2_loops": idx2_p["repeats_forever"],
"repeat_out_of_bounds_rejected": oob_rejected,
}
c2_expected = {
"repeat_minus1_loops": False,
"repeat_2_start_index": 2,
"repeat_2_loops": True,
"repeat_out_of_bounds_rejected": True,
}
# Case 3: Layout 5 buttons, cancel() before switching pattern, VIBRATE normal permission
root = ET.fromstring(VIBRATOR_LAYOUT_XML)
active = False
active = True # start short
active = False # cancel()
c3_actual = {
"button_count": len(root.findall("Button")),
"permission": "android.permission.VIBRATE",
"is_normal_permission": True,
"active_after_cancel": active,
}
c3_expected = {
"button_count": 5,
"permission": "android.permission.VIBRATE",
"is_normal_permission": True,
"active_after_cancel": False,
}
# Case 4: API 26+ VibrationEffect & API 31+ VibratorManager migration
eff_default = vibration_effect_oneshot(300, -1)
eff_custom = vibration_effect_oneshot(150, 180)
c4_actual = {
"api26_oneshot_default": eff_default,
"api26_oneshot_custom": eff_custom,
"api31_service": "Context.VIBRATOR_MANAGER_SERVICE -> VibratorManager.getDefaultVibrator()",
}
c4_expected = {
"api26_oneshot_default": {"type": "ONE_SHOT", "duration_ms": 300, "amplitude": -1},
"api26_oneshot_custom": {"type": "ONE_SHOT", "duration_ms": 150, "amplitude": 180},
"api31_service": "Context.VIBRATOR_MANAGER_SERVICE -> VibratorManager.getDefaultVibrator()",
}
cases = [
{
"name": "vibrator_waveform_duty_cycles",
"summary": "核验短振动/长振动/节奏振动三组 pattern 数组的 [关,开] 交替时长与占空比",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "vibrator_repeat_index_semantics",
"summary": "核验 repeat 参数语义(-1 单次、>=0 表示循环起始下标而非重复次数)与越界校验",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "vibrator_layout_cancel_and_permission",
"summary": "核验五按钮布局解析、cancel() 停止状态与 VIBRATE 普通权限声明",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
{
"name": "vibrator_api26_effect_and_api31_manager",
"summary": "核验 API 26 VibrationEffect.createOneShot 幅度约束与 API 31 VibratorManager 迁移路径",
"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-vibrator-lab/explore-tutorial-vibrator.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-vibrator.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1967.zip