蓝色天空网mbsky.com · 知识 · 实践 · 创造Android · 本地阅读预览
教程 / 移动开发 / Android

10.11 传感器专题(2)——方向传感器

解析 Android 标准三维传感器坐标系、方向传感器方位角/倾斜角/滚动角三元组、替代已废弃 TYPE_ORIENTATION 的 getRotationMatrix + getOrientation 矩阵算法,以及文字指南针实现与正北 360°→0° 边界修复。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

Android 三维传感器坐标系与三轴姿态角含义

Android 传感器框架采用相对设备自然方向(手机默认竖屏)的右手三维坐标系:X 轴沿屏幕水平方向自左向右(短边方向);Y 轴自屏幕左下角沿垂直方向指向上端(长边方向);Z 轴在设备水平面朝上放置时垂直屏幕指向天空。这与 Canvas 绘图坐标系(原点在左上角、Y 轴向下)存在本质区别。

传统方向传感器通过 `SensorEvent.values` 返回 3 个以角度(°)表示的浮点值:`values[0]` 为**方位角(Azimuth)**,即设备绕 Z 轴相对磁北的旋转角,`0°` 为正北、`90°` 为正东、`180°` 为正南、`270°` 为正西,是实现指南针的核心依据;`values[1]` 为**倾斜角(Pitch)**,即绕 X 轴俯仰的角度,范围 `[-180°, 180°]`,水平放置为 `0°`,抬起顶部时向 `-180°` 递减,抬起底部时向 `+180°` 递增;`values[2]` 为**滚动角(Roll)**,即绕 Y 轴翻滚的角度,范围 `[-90°, 90°]`,左侧抬起向 `-90°` 变化,右侧抬起向 `+90°` 变化,结合 Pitch 与 Roll 可制作电子水平仪。

方向读数示例与现代 getRotationMatrix + getOrientation 替代方案

基础演示中,在布局放置三个 `TextView` 分别展示方位角、倾斜角与滚动角,于 `onCreate()` 注册 `SensorEventListener`,在 `onSensorChanged()` 中使用 `(float) Math.round(event.values[i] * 100) / 100` 保留两位小数刷新界面。需重点强调现代 API 规范:`Sensor.TYPE_ORIENTATION` 自 Android 2.2(API 8)起已正式废弃,工程实现应同时监听 `TYPE_ACCELEROMETER`(重力分量)与 `TYPE_MAGNETIC_FIELD`(地磁分量),调用 `SensorManager.getRotationMatrix(R, I, gravity, geomagnetic)` 计算旋转矩阵,再调用 `SensorManager.getOrientation(R, orientationAngles)` 换算弧度制的 `(azimuth, pitch, roll)` 并转为角度。本站离线实验完整实现了 `getRotationMatrix` 与 `getOrientation` 矩阵算法,实测正北 `[0°, 0°, 0°]`、正东 `[90°, 0°, 0°]`、正南 `[180°, 0°, 0°]` 及抬头 `30°`(Pitch `-30°`)与自由落体返回无效矩阵的边界条件。

简易文字指南针实现与正北边界缺陷修正

指南针示例中,自定义 `CompassView` 继承 `View` 并在 `onDraw()` 绘制方位文案,在 `MainActivity` 中将 `event.values[0]` 传入 `cView.setDegree()`,并在 `onDestroy()` 调用 `sManager.unregisterListener(this)` 释放监听。代码审阅需指出两项改进点:第一,原 `CompassView.setDegree()` 用 `dec > 360 - range && dec < 360 + range`(`range=22`)判断正北,但由于方位角在 `0°` 与 `360°` 间首尾相接,当读数为 `5°` 等 `[0°, 22°]` 区间值时该条件完全漏判,正确写法应以环形角差 `abs(((d - center + 180) % 360) - 180) <= 22.5` 统一覆盖八个方位(本站实验已对比复现并验证修复);第二,示例在自定义 `View` 构造函数里新开无限循环线程每 `100ms` 调用 `postInvalidate()`,若未在 `onDetachedFromWindow()` 中断线程易造成泄漏,直接于 `setDegree()` 角度变动时调用 `invalidate()` 更为简洁省电。来源附带的 `SensorDemo2.zip` 与 `SensorDemo3.zip` 因继承停采策略未联网下载,已分别登记留痕。

运行离线旋转矩阵姿态角(getRotationMatrix + getOrientation)与指南针八方位修复核验

python · 阅读源码
"""Offline Android sensor verifier for Ch 146: Orientation Sensor & Rotation Matrix Math."""
import json
import math


VERSION = (
    "CPython 3.12.14 offline Android system-service/sensor/capstone verifier "
    "(Android SDK/emulator absent)"
)


def get_rotation_matrix(gravity: tuple[float, float, float], geomagnetic: tuple[float, float, float]) -> list[float] | None:
    """Port of Android SensorManager.getRotationMatrix(R, I, gravity, geomagnetic)."""
    ax, ay, az = gravity
    ex, ey, ez = geomagnetic
    norm_sq_a = ax * ax + ay * ay + az * az
    if norm_sq_a < 0.01 * (9.81 ** 2):
        return None
    # H = E x A (points East)
    hx = ey * az - ez * ay
    hy = ez * ax - ex * az
    hz = ex * ay - ey * ax
    norm_h = math.sqrt(hx * hx + hy * hy + hz * hz)
    if norm_h < 0.1:
        return None
    inv_h = 1.0 / norm_h
    hx, hy, hz = hx * inv_h, hy * inv_h, hz * inv_h
    inv_a = 1.0 / math.sqrt(norm_sq_a)
    ax, ay, az = ax * inv_a, ay * inv_a, az * inv_a
    # M = A x H (points Magnetic North)
    mx = ay * hz - az * hy
    my = az * hx - ax * hz
    mz = ax * hy - ay * hx
    return [hx, hy, hz, mx, my, mz, ax, ay, az]


def get_orientation(r: list[float]) -> tuple[float, float, float]:
    """Port of Android SensorManager.getOrientation(R, values) returning degrees (azimuth_360, pitch, roll)."""
    az_rad = math.atan2(r[1], r[4])
    pitch_rad = math.asin(-r[7])
    roll_rad = math.atan2(-r[6], r[8])
    az_deg = (math.degrees(az_rad) + 360.0) % 360.0
    pitch_deg = math.degrees(pitch_rad)
    roll_deg = math.degrees(roll_rad)
    return (round(az_deg, 2), round(pitch_deg, 2), round(roll_deg, 2))


def classify_compass_fixed(degree: float, half_range: float = 22.5) -> str:
    """Correct 8-sector compass classifier handling 360->0 wraparound cleanly."""
    d = degree % 360.0
    sectors = [
        (0.0, "正北"),
        (45.0, "东北"),
        (90.0, "正东"),
        (135.0, "东南"),
        (180.0, "正南"),
        (225.0, "西南"),
        (270.0, "正西"),
        (315.0, "西北"),
    ]
    for center, label in sectors:
        diff = abs(((d - center + 180.0) % 360.0) - 180.0)
        if diff <= half_range:
            return label
    return "正北"


def classify_compass_legacy_bug(degree: float, range_deg: int = 22) -> str | None:
    """Reproduce source CompassView bug where (360-range < dec < 360+range) misses [0, 22]."""
    if degree > 360 - range_deg and degree < 360 + range_deg:
        return "正北"
    for center, label in ((90, "正东"), (180, "正南"), (270, "正西"), (45, "东北"), (135, "东南"), (225, "西南"), (315, "西北")):
        if degree > center - range_deg and degree < center + range_deg:
            return label
    return None


def main() -> None:
    # Case 1: SensorManager.getRotationMatrix + getOrientation replacing deprecated TYPE_ORIENTATION
    # Flat device facing North: gravity=(0,0,9.81), magnetic field=(0, 30, -40) (North +Y, dipped downward -Z)
    r_north = get_rotation_matrix((0.0, 0.0, 9.81), (0.0, 30.0, -40.0))
    # Flat device rotated 90 deg clockwise (facing East): North is now along -X => geomagnetic=(-30, 0, -40)
    r_east = get_rotation_matrix((0.0, 0.0, 9.81), (-30.0, 0.0, -40.0))
    # Flat device facing South: geomagnetic=(0, -30, -40)
    r_south = get_rotation_matrix((0.0, 0.0, 9.81), (0.0, -30.0, -40.0))
    # Device facing North, pitched up 30 deg around X axis: gravity=(0, 9.81*sin30, 9.81*cos30)
    g_pitch30 = (0.0, 9.81 * math.sin(math.radians(30)), 9.81 * math.cos(math.radians(30)))
    m_pitch30 = (0.0, 30.0 * math.cos(math.radians(30)), -30.0 * math.sin(math.radians(30)))
    r_pitch = get_rotation_matrix(g_pitch30, m_pitch30)

    assert r_north and r_east and r_south and r_pitch
    c1_actual = {
        "facing_north_deg": list(get_orientation(r_north)),
        "facing_east_deg": list(get_orientation(r_east)),
        "facing_south_deg": list(get_orientation(r_south)),
        "pitched_up_30_deg": list(get_orientation(r_pitch)),
        "freefall_returns_none": get_rotation_matrix((0.0, 0.0, 0.0), (0.0, 30.0, -40.0)) is None,
    }
    c1_expected = {
        "facing_north_deg": [0.0, 0.0, 0.0],
        "facing_east_deg": [90.0, 0.0, 0.0],
        "facing_south_deg": [180.0, 0.0, 0.0],
        "pitched_up_30_deg": [0.0, -30.0, 0.0],
        "freefall_returns_none": True,
    }

    # Case 2: Text display rounding & CompassView 8-direction classification + North wraparound bugfix
    sample_values = (182.346, -12.456, 4.123)
    formatted = [round(v * 100) / 100 for v in sample_values]
    test_angles = [5.0, 45.0, 90.0, 135.0, 180.0, 225.0, 270.0, 315.0, 355.0]
    fixed_labels = [classify_compass_fixed(a) for a in test_angles]
    legacy_5deg = classify_compass_legacy_bug(5.0)
    fixed_5deg = classify_compass_fixed(5.0)

    c2_actual = {
        "rounded_display_values": formatted,
        "fixed_9_angles": fixed_labels,
        "legacy_bug_at_5deg_returns_none": legacy_5deg is None,
        "fixed_at_5deg": fixed_5deg,
    }
    c2_expected = {
        "rounded_display_values": [182.35, -12.46, 4.12],
        "fixed_9_angles": ["正北", "东北", "正东", "东南", "正南", "西南", "正西", "西北", "正北"],
        "legacy_bug_at_5deg_returns_none": True,
        "fixed_at_5deg": "正北",
    }

    cases = [
        {
            "name": "rotation_matrix_orientation_math",
            "summary": "使用 getRotationMatrix + getOrientation 替代已废弃 TYPE_ORIENTATION,核验北/东/南与30°俯仰姿态角",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "compass_sector_and_north_wraparound_fix",
            "summary": "验证指南针读数保留两位小数、8 方位划分及 360°→0° 跨越正北区间漏判缺陷修复",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 验证北/东/南与30°俯仰的旋转矩阵欧拉角输出、两位小数舍入及 5° 正北区间漏判修复。
运行离线旋转矩阵姿态角(getRotationMatrix + getOrientation)与指南针八方位修复核验

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

当前源码 SHA256:780abe1236fbd49743decc8a73c2fea43442f159b33cdb31ffb7b0f5370568c2

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载10.11 传感器专题(2)——方向传感器实验

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

ZIP SHA256:38070c4349720d8b5533d70159393c8f247be3f6999eff3ab5a30735fc37cd45

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

既然 `Sensor.TYPE_ORIENTATION` 在 Android 2.2 起已被废弃,现代 Android 应用应如何正确计算设备方位角?

展开参考解答

应分别注册 `Sensor.TYPE_ACCELEROMETER` 和 `Sensor.TYPE_MAGNETIC_FIELD`,调用 `SensorManager.getRotationMatrix()` 构造旋转矩阵后再通过 `SensorManager.getOrientation()` 获取弧度制方位角、俯仰角和滚转角(或直接使用 `TYPE_ROTATION_VECTOR`)。

规范与官方依据