首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在phonegap中使用acclerometer检测移动

在phonegap中使用acclerometer检测移动
EN

Stack Overflow用户
提问于 2019-04-18 21:11:56
回答 1查看 491关注 0票数 0

我正在做一个应用程序,所以我想使用加速度计来检测用户是否移动了设备,所以我想知道如何通过将加速度计插件添加到config.xml文件中来将其添加到PhoneGap构建应用程序中,以及如何使用javascript每隔20 - 30毫秒在应用程序中检查设备移动情况?

EN

回答 1

Stack Overflow用户

发布于 2019-04-18 21:40:29

Cordova要在Cordova应用程序中安装插件,请运行以下命令:

代码语言:javascript
运行
复制
cordova plugin add cordova-plugin-device-motion 

PhoneGap要将插件添加到您的PhoneGap应用程序,请在您的config.xml中添加以下内容:

代码语言:javascript
运行
复制
<plugin name="cordova-plugin-device-motion" />

代码:

代码语言:javascript
运行
复制
<!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>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55746772

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档