javascript - 在phonegap中使用加速度计检测运动
问题描述
我正在制作一个应用程序,所以我想使用加速度计来检测用户是否移动了设备,所以我想知道如何通过将加速度计插件添加到 config.xml 文件中来将其包含到 PhoneGap 构建应用程序中,以及如何我使用javascript每20-30毫秒检查一次应用程序中的设备移动吗?
解决方案
Cordova 要在您的 Cordova 应用程序中安装插件,请运行以下命令:
cordova plugin add cordova-plugin-device-motion
PhoneGap 要将插件添加到您的 PhoneGap 应用程序,请将以下内容添加到您的 config.xml:
<plugin name="cordova-plugin-device-motion" />
代码:
<!DOCTYPE html>
<html>
<head>
<title>Acceleration Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-x.x.x.js"></script>
<script type="text/javascript" charset="utf-8">
// The watch id references the current `watchAcceleration`
var watchID = null;
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
startWatch();
}
// Start watching the acceleration
//
function startWatch() {
// Update acceleration every 3 seconds
var options = { frequency: 30 };
watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
}
// Stop watching the acceleration
//
function stopWatch() {
if (watchID) {
navigator.accelerometer.clearWatch(watchID);
watchID = null;
}
}
// onSuccess: Get a snapshot of the current acceleration
//
function onSuccess(acceleration) {
var element = document.getElementById('accelerometer');
element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' +
'Acceleration Y: ' + acceleration.y + '<br />' +
'Acceleration Z: ' + acceleration.z + '<br />' +
'Timestamp: ' + acceleration.timestamp + '<br />';
}
// onError: Failed to get the acceleration
//
function onError() {
alert('onError!');
}
</script>
</head>
<body>
<div id="accelerometer">Waiting for accelerometer...</div>
</body>
</html>
推荐阅读
- javascript - Json 和 ajax Html 表
- c++ - 哈希表 - 调整崩溃程序的大小
- python - 您如何将另一个类方法的“标题”中的类方法引用为默认变量?
- reactjs - 如何映射 Firebase 数据库?
- vb.net - 我收到一个我无法修复的错误(Windows 窗体应用程序 vbnet)
- git - git restore submodules - 创建子模块目录但为空
- python-3.x - 使用 selenium webdriver 从网页中提取日期
- makefile - 如何按一定顺序调用子目录中的make?
- c++ - 让 g++ 对促销发出警告
- bash - Bash 语法错误:意外标记“else”附近的语法错误