"""Offline Android media verifier for Ch 134: Camera Capture & Camera2/CameraX Migration."""
import json
import xml.etree.ElementTree as ET
VERSION = "CPython 3.12.14 offline Android graphics/animation/media/service verifier (Android SDK/emulator absent)"
CAMERA_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">
<SurfaceView android:id="@+id/sfv_preview" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" />
<Button android:id="@+id/btn_take" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="拍照" />
</LinearLayout>
"""
class CameraHardwareLock:
def __init__(self) -> None:
self.owner: str | None = None
self.previewing = False
self.orientation_deg = 0
def open(self, caller: str) -> None:
if self.owner is not None:
raise RuntimeError("java.lang.RuntimeException: fail to connect to camera service")
self.owner = caller
def set_display_orientation(self, deg: int) -> None:
if deg not in (0, 90, 180, 270):
raise ValueError("Orientation must be multiple of 90")
self.orientation_deg = deg
def start_preview(self) -> None:
if self.owner is None:
raise RuntimeError("Camera not open")
self.previewing = True
def stop_preview(self) -> None:
self.previewing = False
def release(self) -> None:
self.previewing = False
self.owner = None
def main() -> None:
# Case 1: System camera Intent (ACTION_IMAGE_CAPTURE) thumbnail vs EXTRA_OUTPUT & source bug audit
# Note: Activity.DEFAULT_KEYS_DIALER == 1, Activity.RESULT_OK == -1!
# So checking `requestCode == Activity.RESULT_OK` is ALWAYS False when requestCode=1!
req_code = 1 # Activity.DEFAULT_KEYS_DIALER
res_code = -1 # Activity.RESULT_OK
buggy_check = (req_code == res_code)
fixed_check = (req_code == 1 and res_code == -1)
# Also `if (dir.exists()) dir.mkdirs()` was inverted; should be `if (!dir.exists()) dir.mkdirs()`
c1_actual = {
"action": "android.media.action.IMAGE_CAPTURE",
"buggy_requestCode_eq_RESULT_OK": buggy_check,
"fixed_request_and_result_check": fixed_check,
"extra_output_uri_scheme_api24_plus": "content://",
}
c1_expected = {
"action": "android.media.action.IMAGE_CAPTURE",
"buggy_requestCode_eq_RESULT_OK": False,
"fixed_request_and_result_check": True,
"extra_output_uri_scheme_api24_plus": "content://",
}
# Case 2: Camera1 exclusive hardware lock & release() preventing "fail to connect to camera service"
hw = CameraHardwareLock()
hw.open("MainActivity")
hw.set_display_orientation(90)
hw.start_preview()
reopen_error = ""
try:
hw.open("SecondCaller")
except RuntimeError as exc:
reopen_error = str(exc)
hw.stop_preview()
hw.release()
hw.open("SecondCaller")
reopen_ok = hw.owner == "SecondCaller"
hw.release()
c2_actual = {
"orientation_deg": 90,
"unreleased_reopen_error": reopen_error,
"reopen_after_release_ok": reopen_ok,
}
c2_expected = {
"orientation_deg": 90,
"unreleased_reopen_error": "java.lang.RuntimeException: fail to connect to camera service",
"reopen_after_release_ok": True,
}
# Case 3: Custom camera layout & manifest permissions
root = ET.fromstring(CAMERA_LAYOUT_XML)
manifest_perms = ["android.permission.CAMERA", "android.permission.WRITE_EXTERNAL_STORAGE"]
c3_actual = {
"has_surface_and_button": (root.find("SurfaceView") is not None and root.find("Button") is not None),
"legacy_manifest_permissions": manifest_perms,
"runtime_permission_min_api": 23,
}
c3_expected = {
"has_surface_and_button": True,
"legacy_manifest_permissions": ["android.permission.CAMERA", "android.permission.WRITE_EXTERNAL_STORAGE"],
"runtime_permission_min_api": 23,
}
# Case 4: Camera1 -> Camera2 / CameraX migration matrix & FileProvider compliance
migration = {
"deprecated_api": "android.hardware.Camera (deprecated API 21)",
"low_level_replacement": "android.hardware.camera2",
"recommended_jetpack": "androidx.camera (CameraX Preview + ImageCapture)",
"file_uri_replacement_api24": "FileProvider.getUriForFile()",
"background_silent_camera_blocked_api28_plus": True,
}
c4_actual = migration
c4_expected = {
"deprecated_api": "android.hardware.Camera (deprecated API 21)",
"low_level_replacement": "android.hardware.camera2",
"recommended_jetpack": "androidx.camera (CameraX Preview + ImageCapture)",
"file_uri_replacement_api24": "FileProvider.getUriForFile()",
"background_silent_camera_blocked_api28_plus": True,
}
cases = [
{
"name": "camera_intent_result_code_and_fileprovider",
"summary": "核验 ACTION_IMAGE_CAPTURE 缩略图与 EXTRA_OUTPUT 回调中 requestCode/resultCode 混用缺陷及 API 24+ content:// URI",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "camera1_exclusive_lock_and_release",
"summary": "核验 Camera.open() 独占锁未 release() 触发 fail to connect to camera service 及正确释放后的复连",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "custom_camera_layout_and_permissions",
"summary": "核验自定义拍照页 SurfaceView+Button 布局及 CAMERA/存储权限与 API 23 运行时授权门槛",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
{
"name": "camera2_camerax_migration_and_privacy",
"summary": "核验 Camera1 废弃后向 Camera2/CameraX 迁移路径、FileProvider 替换及现代隐私合规限制",
"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-camera-lab/explore-tutorial-camera.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-camera.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1852.zip