我們將用cordova-CLI來安裝這個(gè)插件。在命令提示符窗口鍵入下面的代碼。
D:\worksp\cordova\CordovaProject>cordova plugin add cordova-plugin-device-motion
我們需要做的下一件事就是在 index.html 文件中添加兩個(gè)按鈕。一個(gè)將被用于獲取當(dāng)前加速度并其他將觀察加速度的變化。
<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>
document.getElementById("getAcceleration").addEventListener("click", getAcceleration);
document.getElementById("watchAcceleration").addEventListener("click", watchAcceleration);
我們將創(chuàng)建兩個(gè)函數(shù)。第一個(gè)將被用來獲取當(dāng)前加速度,第二個(gè)會看加速度并每隔三秒鐘告知我們。我們也通過添加clearWatch setTimeout函數(shù)包裝停止指定的時(shí)間幀之后監(jiān)視加速度。頻率(frequency)參數(shù)用于每三秒觸發(fā)回調(diào)函數(shù)。
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!');
};
}
現(xiàn)在,如果我們按GET ACCELERATION按鈕將獲得當(dāng)前加速度值。如果我們按WATCH ACCELERATION警告提示將每三秒鐘觸發(fā)。第三警告提示顯示后,clearWatch函數(shù)將被調(diào)用,因?yàn)槲覀冊O(shè)置超時(shí)時(shí)間為10000毫秒,所以不會得到任何更多的警報(bào)。
