首页 > 解决方案 > 在phonegap中使用加速度计检测运动

问题描述

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

标签: javascriptandroidcordovaaccelerometerphonegap

解决方案


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>

推荐阅读