使用PhoneGap中的加速度计检测运动

时间:2019-04-18 13:11:56

标签: javascript android cordova accelerometer phonegap

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

1 个答案:

答案 0 :(得分: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>