该插件也被称为设备运动。 它用来在三个维度来跟踪设备的运动。
第1步 - 安装加速度传感器插件
我们将用cordova-CLI来安装这个插件。在命令提示符窗口键入下面的代码。
D:\worksp\cordova\CordovaProject>cordova plugin add cordova-plugin-device-motion
第2步 - 添加按钮
我们需要做的下一件事就是在 index.html 文件中添加两个按钮。一个将被用于获取当前加速度并其他将观察加速度的变化。
<body> <div class="app"> <h1>Cordova加速度传感器</h1> <button id = "getAcceleration">GET ACCELERATION</button> <button id = "watchAcceleration">WATCH ACCELERATION</button> </div> <script type="text/javascript" src="cordova.js"></script> <script type="text/javascript" src="js/index.js"></script> </body>
第3步 - 添加事件监听器
将按钮添加到 index.js 中的事件侦听器 onDeviceReady 函数内部(放在前面)。
document.getElementById("getAcceleration").addEventListener("click", getAcceleration); document.getElementById("watchAcceleration").addEventListener("click", watchAcceleration);
第4步 - 创建函数
我们将创建两个函数。第一个将被用来获取当前加速度,第二个会看加速度并每隔三秒钟告知我们。我们也通过添加clearWatch setTimeout函数包装停止指定的时间帧之后监视加速度。频率(frequency)参数用于每三秒触发回调函数。
function getAcceleration(){ navigator.accelerometer.getCurrentAcceleration(accelerometerSuccess, accelerometerError); function accelerometerSuccess(acceleration) { alert('Acceleration X: ' + acceleration.x + '\n' + 'Acceleration Y: ' + acceleration.y + '\n' + 'Acceleration Z: ' + acceleration.z + '\n' + 'Timestamp: ' + acceleration.timestamp + '\n'); }; function accelerometerError() { alert('onError!'); }; } function watchAcceleration(){ var accelerometerOptions = { frequency: 3000 } var watchID = navigator.accelerometer.watchAcceleration(accelerometerSuccess, accelerometerError, accelerometerOptions); function accelerometerSuccess(acceleration) { alert('Acceleration X: ' + acceleration.x + '\n' + 'Acceleration Y: ' + acceleration.y + '\n' + 'Acceleration Z: ' + acceleration.z + '\n' + 'Timestamp: ' + acceleration.timestamp + '\n'); setTimeout(function() { navigator.accelerometer.clearWatch(watchID); }, 10000); }; function accelerometerError() { alert('onError!'); }; }
现在,如果我们按GET ACCELERATION按钮将获得当前加速度值。如果我们按WATCH ACCELERATION警告提示将每三秒钟触发。第三警告提示显示后,clearWatch函数将被调用,因为我们设置超时时间为10000毫秒,所以不会得到任何更多的警报。

上一篇:
Cordova设备信息
下一篇:
Cordova设备方向