@capacitor/motion
Motion API 跟踪加速度计和设备方向(指南针方向等)。
安装
npm install @capacitor/motion
npx cap sync
权限
此插件目前使用 Web API 实现。大多数浏览器需要在使用此 API 前获得权限。要请求权限,在用户发起的任何操作(如按钮点击)上提示用户授予权限:
import { PluginListenerHandle } from '@capacitor/core';
import { Motion } from '@capacitor/motion';
let accelHandler: PluginListenerHandle;
myButton.addEventListener('click', async () => {
try {
await DeviceMotionEvent.requestPermission();
} catch (e) {
// 处理错误
return;
}
// 用户批准后,可以开始监听:
accelHandler = await Motion.addListener('accel', event => {
console.log('Device motion event:', event);
});
});
// 停止加速度监听器
const stopAcceleration = () => {
if (accelHandler) {
accelHandler.remove();
}
};
// 移除所有监听器
const removeListeners = () => {
Motion.removeAllListeners();
};