官术网_书友最值得收藏!

Adjusting the accelerometer sensor update interval

The getCurrentAcceleration method obtains data from the accelerometer at the time it was called - a single call to obtain a single response object. In this recipe, we'll build an application that allows us to set an interval to obtain a constant update from the accelerometer to detect continual movement from the device.

How to do it…

We will provide additional parameters to a new method available through the PhoneGap API to set the update interval:

  1. First, create a new PhoneGap project named accelupdate. Open Terminal or Command Prompt and run the following command:
    phonegap create accelupdate com.myapp.accelupdate accelupate
    
  2. Add the devices platform. You can choose to use Android, iOS, or both:
    cordova platform add ios
    cordova platform add android
    
  3. Add the device-motion plugin by running the following command:
    phonegap plugin add org.apache.cordova.device-motion
    
  4. Open www/index.html and clean up unnecessary elements; so you have the following:
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8" />
            <meta name="format-detection" content="telephone=no" />
            <meta name="msapplication-tap-highlight" content="no" />
            <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height,
            target-densitydpi=device-dpi" />
            <link rel="stylesheet" type="text/css" href="css/index.css" />
            <title>Hello World</title>
        </head>
        <body>
            <h1>Accelerometer Data</h1>
            <div id="accelerometerData">Obtaining data…</div>
    
            <script type="text/javascript" src="cordova.js"></script>
            <script type="text/javascript">
    
            </script>
        </body>
    </html>
  5. Below the Cordova JavaScript reference, write a new JavaScript tag block, within which a variable called watchID will be declared.
  6. Next, define an event listener to ensure that the device is ready and the native code has loaded before continuing:
    <script type="text/javascript">
          // The watch id variable is set as a
          // reference to the current 'watchAcceleration'
          var watchID = null;
          // Set the event listener to run
          // when the device is ready
          document.addEventListener('deviceready', onDeviceReady, false);
    </script>
  7. Now add in the onDeviceReady function, which will run a method called startWatch once the native code has fully loaded:
    // The device is ready so let's
    // start watching the acceleration
     function onDeviceReady() {
           startWatch();
    }
  8. Next, write the startWatch function. To do this, first, create a variable called options to hold the optional frequency parameter, set to 3,000 milliseconds (3 seconds).
  9. Then, set the initial disabled properties of two buttons that will allow the user to start and stop the acceleration detection.
  10. Next, assign the watchAcceleration to the previously defined watchID variable. This will allow you to check for a value or identify if it is still set to null.
  11. Apart from defining the success and error function names, you are also sending the options variable into the method call, which contains the frequency value:
    // Watch the acceleration at regular
    // intervals as set by the frequency
    function startWatch() {
    
        // Set the frequency of updates
        // from the acceleration
        var options = { frequency: 3000 };
    
        // Set attributes for control buttons
        document.getElementById('startBtn').disabled = true;
        document.getElementById('stopBtn').disabled = false;
    
        // Assign watchAcceleration to the watchID variable
        // and pass through the options array
        watchID = navigator.accelerometer.watchAcceleration(
        onSuccess, onError, options);
    }
  12. With the startWatch function written, you now need to provide a method to stop the detection of the acceleration. This firstly checks the value of the watchID variable. If this is not null, it will stop watching the acceleration using the clearWatch method, passing in the watchID parameter before resetting this variable back to null.
  13. Then reference the accelerometer div element and set its value to a user-friendly message.
  14. Next, reassign the disabled properties for both the control buttons to allow the user to start watching again, as follows:
    // Stop watching the acceleration
    function stopWatch() {
    
        if (watchID) {
            navigator.accelerometer.clearWatch(watchID);
          watchID = null;
    
            var element =
                document.getElementById('accelerometerData');
    
            element.innerHTML =
                'No longer watching your acceleration.';
    
            // Set attributes for control buttons
            document.getElementById('startBtn').disabled = false;
            document.getElementById('stopBtn').disabled = true;
    
        }
    }
  15. Now, create the onSuccess method, which will be run after a successful update response. Assign the returned values from the acceleration object as the HTML within the accelerometer div element for display to the user—the available properties are accessed through the acceleration object and applied to the string variable:
    // Run after successful transaction
    // Let's display the accelerometer data
    function onSuccess(acceleration) {
        var element = document.getElementById('accelerometerData');
        element.innerHTML =
            'Acceleration X: ' + acceleration.x + '<br />' +
            'Acceleration Y: ' + acceleration.y + '<br />' +
          'Acceleration Z: ' + acceleration.z + '<br />' +
          'Timestamp: '      + acceleration.timestamp +
          '<br />';
    }
  16. You also need to supply the onError method to catch any possible issues with the request. Here, output a user-friendly message, setting it as the value of the accelerometerData div element:
    // Run if we face an error
    // obtaining the accelerometer data
    function onError() {
        // Handle any errors we may face
        var element = document.getElementById('accelerometerData');
        element.innerHTML =
            'Sorry, I was unable to access the acceleration data.';
    }
  17. Finally, add in the two button elements, both of which will have an onClick attribute set to either start or stop watching the device acceleration:
    <body>
        <h1>Accelerometer Data</h1>
    
        <button id="startBtn" onclick="startWatch()">start</button>
    
        <button id="stopBtn" onclick="stopWatch()">stop</button>
    
        <div id="accelerometerData">Obtaining data...</div>
    
    </body>
  18. The results will appear similar to the following screenshot:
    How to do it…
  19. Stopping the acceleration watch will result something like this:
    How to do it…

How it works…

By registering an event listener to the deviceready event, we ensure that the JavaScript code does not run before the native PhoneGap code is executed. Once ready, the application calls the startWatch function, within which the desired frequency interval for the acceleration updates is set.

The watchAcceleration method from the PhoneGap API retrieves the device's current acceleration data at the specified interval. If not, as the interval is passed through, it defaults to 10,000 milliseconds (10 seconds). Each time an update has been obtained, the onSuccess method is run to handle the data as you wish—in this case, displaying the results on the screen.

The watchID variable contains a reference to the watch interval and is used to stop the watching process by passing it into the clearWatch method from the PhoneGap API.

There's more…

In this example, the frequency value for the accelerometer update interval was set at 3,000 milliseconds (3 seconds). Consider writing a variation on this application that allows the user to manually change the interval value using a slider, or by setting the desired value into an input box.

See also…

主站蜘蛛池模板: 额尔古纳市| 绩溪县| 昂仁县| 西贡区| 白水县| 平潭县| 贞丰县| 通道| 富裕县| 望谟县| 乐都县| 上虞市| 台山市| 措勤县| 留坝县| 巴东县| 辽宁省| 五常市| 昆山市| 拜泉县| 沧州市| 通州区| 于田县| 广汉市| 九龙县| 长乐市| 双城市| 甘孜| 疏附县| 江永县| 新绛县| 峨山| 巴中市| 新昌县| 云南省| 宁乡县| 沿河| 鱼台县| 德化县| 离岛区| 枣阳市|