該插件也被稱為設備運動。 它用來在三個維度來跟蹤設備的運動。
第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設備方向