Skip to content

Cordova - 加速计

Apache Cordova Device Motion plugin (设备运动插件,历史上称为 Accelerometer plugin) 提供了访问设备加速度计的能力。加速度计是一种运动传感器,它检测相对于当前设备方向在 x、y 和 z 轴上三个维度上的运动变化(delta)。

此插件提供了 navigator.accelerometer 对象,其中包含获取当前加速度和监听加速度变化的方法。

使用 Cordova CLI (命令行界面) 安装插件。确保你位于项目的根目录。

cordova plugin add cordova-plugin-device-motion

添加插件后,请务必构建你的项目:cordova build <platform>(例如 cordova build android)。

在你的 www/index.html 文件中,添加按钮来触发加速度计操作,并添加一个占位符来显示数据。这比使用 alert() 更容易查看结果。

<body>
<h1>加速度计演示</h1>
<button id="getAccelerationBtn">获取当前加速度</button>
<button id="watchAccelerationBtn">开始监听加速度</button>
<button id="stopWatchAccelerationBtn">停止监听加速度</button>
<div id="accelerometerData">
<p>X 轴: <span id="accelX">N/A</span></p>
<p>Y 轴: <span id="accelY">N/A</span></p>
<p>Z 轴: <span id="accelZ">N/A</span></p>
<p>时间戳: <span id="accelTimestamp">N/A</span></p>
</div>
<script src="cordova.js"></script>
<script src="js/index.js"></script>
</body>

在你的 www/js/index.js 文件中,在 onDeviceReady 函数内部,添加事件监听器并实现与加速度计交互的函数。请记住,Cordova 插件 API (应用程序接口) 仅在 deviceready 事件触发后可用。

document.addEventListener('deviceready', onDeviceReady, false);
let watchID = null;
function onDeviceReady() {
console.log('设备已就绪。');
document.getElementById('getAccelerationBtn').addEventListener('click', getCurrentAcceleration);
document.getElementById('watchAccelerationBtn').addEventListener('click', startWatchAcceleration);
document.getElementById('stopWatchAccelerationBtn').addEventListener('click', stopWatchAcceleration);
}
function updateAccelerationUI(acceleration) {
document.getElementById('accelX').textContent = acceleration.x.toFixed(2);
document.getElementById('accelY').textContent = acceleration.y.toFixed(2);
document.getElementById('accelZ').textContent = acceleration.z.toFixed(2);
document.getElementById('accelTimestamp').textContent = new Date(acceleration.timestamp).toLocaleTimeString();
}
function accelerometerError(error) {
console.error('加速度计错误:', error);
alert('加速度计错误:' + (error.message || '未知错误'));
}
// 获取当前加速度
function getCurrentAcceleration() {
navigator.accelerometer.getCurrentAcceleration(updateAccelerationUI, accelerometerError);
}
// 开始监听加速度
function startWatchAcceleration() {
if (watchID) { // 已在监听
console.log('已在监听加速度。');
return;
}
const options = { frequency: 1000 }; // 每 1 秒更新一次 (1000 毫秒)
watchID = navigator.accelerometer.watchAcceleration(
(acceleration) => {
console.log('正在监听加速度:', acceleration);
updateAccelerationUI(acceleration);
},
accelerometerError,
options
);
console.log('已开始监听加速度,watchID:' + watchID);
document.getElementById('watchAccelerationBtn').disabled = true;
document.getElementById('stopWatchAccelerationBtn').disabled = false;
}
// 停止监听加速度
function stopWatchAcceleration() {
if (watchID) {
navigator.accelerometer.clearWatch(watchID);
watchID = null;
console.log('已停止监听加速度。');
document.getElementById('watchAccelerationBtn').disabled = false;
document.getElementById('stopWatchAccelerationBtn').disabled = true;
} else {
console.log('当前未在监听加速度。');
}
}

加速度值 (x, y, z) 的单位是 m/s^2,并包含了重力加速度。例如,一个平放在桌面上的设备,其中一个轴的读数将大约为 +9.81 m/s^2。

  • x:x 轴上的加速度。
  • y:y 轴上的加速度。
  • z:z 轴上的加速度。
  • timestamp:创建时的时间戳(毫秒)。

加速度计可用于:

  • 手势检测:检测晃动、倾斜或特定的设备移动。
  • 游戏:通过设备运动控制角色或游戏元素。
  • 方向检测:补充方向数据,尽管对于简单的屏幕旋转,Screen Orientation 插件或 window.orientation 可能更直接。
  • 健康和健身应用:计步器类功能(尽管专用的计步器 API 通常更准确)。
  • deviceready 事件:务必确保在 deviceready 事件触发后才调用 navigator.accelerometer。
  • 错误处理:实现 onError 回调以管理加速度计可能不可用或发生错误的情况。
  • 频率:注意 watchAcceleration 中的 frequency 选项。高频率会消耗更多电量。选择适合你应用程序需求的速率。
  • 清除监听器:当你不再需要监听加速度时(例如,用户离开该功能或应用程序暂停时),务必调用 clearWatch 以节省电量。上面的示例展示了手动停止,但你也可以钩入 pause 事件。
  • 权限:虽然通常不需要像相机或地理位置那样明确的用户权限提示,但在某些平台上或特定上下文中,访问仍可能受到设备策略的限制。

有关更多详细信息,请参阅官方文档:Cordova Device Motion Plugin。