【问题标题】:Detecting movement using acclerometer in phonegap在phonegap中使用加速度计检测运动
【发布时间】:2019-04-18 13:11:55
【问题描述】:

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

【问题讨论】:

    标签: javascript android cordova accelerometer phonegap


    【解决方案1】:

    科尔多瓦 要在您的 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>
    

    【讨论】:

    • 我尝试了你的方法,但它不起作用,当我构建它白色 PhoneGap 构建并安装应用程序时,它只显示“等待加速度计.....”它与 apk 签名或某事
    • 确保 cordova.js 有效。你需要先构建你的手机,如果你想添加按钮来获得加速添加到 js 函数 getAcceleration(){ navigator.accelerometer.getCurrentAcceleration(onAccelSuccess, onError); } 并将

      添加到正文
    猜你喜欢
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    相关资源
    最近更新 更多