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

Detecting device movement using the accelerometer

The accelerometer captures device motion in the x, y, and z axis direction. The accelerometer is a motion sensor that detects change (delta) in movement relative to the orientation of the current device.

How to do it…

We will use the accelerometer functionality from the plugins to monitor the feedback from the device:

  1. First, create a new PhoneGap project named accelerometer. Open Terminal or Command Prompt and run the following command:
    phonegap create accelerometer com.myapp.accelerometer accelerometer
    
  2. Add the device's 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 and define an event listener to ensure that the device is ready and the native code has loaded before continuing:
    <script type="text/javascript">
          // Set the event listener to run
          // when the device is ready
          document.addEventListener('deviceready', onDeviceReady, false);
    </script>
  6. Now add in the onDeviceReady function, which will run the getCurrentAcceleration method when the native code has fully loaded:
    // The device is ready so let's
    // obtain the current accelerometer data
    function onDeviceReady() {
         navigator.accelerometer.getCurrentAcceleration(
         onSuccess, onError);
    }
  7. Include the onSuccess function to handle the returned information from the accelerometer.
  8. Define the accelerometer div element to the accElement variable to hold the generated accelerometer results.
  9. Next, 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:
    // Run after successful transaction
    // Let's display the accelerometer data
    function onSuccess(acceleration) {
        var accElement =
            document.getElementById('accelerometerData');
    
        accElement.innerHTML    =
            'Acceleration X: ' + acceleration.x + '<br />' +
          'Acceleration Y: ' + acceleration.y + '<br />' +
            'Acceleration Z: ' + acceleration.z + '<br />' +
            'Timestamp: '      + acceleration.timestamp;
    }
  10. Finally, include the onError function to deal with any possible issues:
    // Run if we face an error
    // obtaining the accelerometer data
    function onError(error) {
        // Handle any errors we may face
        alert('error');
    }
  11. Build and run the project:
    cordova build android
    cordova run android
    
  12. When running the application on an emulator, the output will look something like this:
    How to do it…

How it works…

By registering an event listener to the deviceready event, we are ensuring that the JavaScript code does not run before the native PhoneGap code is executed. Once ready, the application will call the getCurrentAcceleration method from the accelerometer API, providing two methods to handle successful transactions and errors respectively.

The onSuccess function returns the obtained acceleration information in the form of the following four properties:

  • acceleration.x: This is a Number registered in meters per second squared (m/s^2) that measures the device acceleration across the x axis. This is the movement from left to right when the device is placed with the screen in an upright position. Positive acceleration is obtained as the device is moved to the right, whereas a negative movement is obtained when the device is moved to the left.
  • acceleration.y: This is a Number registered in m/s^2 that measures the device acceleration across the y axis. This is the movement from bottom to top when the device is placed with the screen facing an upright position. Positive acceleration is obtained as the device is moved upwards, whereas a negative movement is obtained when the device is moved downwards.
  • acceleration.z: This is a Number registered in m/s^2 that measures the device acceleration across the z axis. This is perpendicular from the face of the device. Positive acceleration is obtained when the device is moved to face towards the sky, whereas a negative movement is obtained when the device is pointed towards the Earth.
  • acceleration.timestamp: This is a DOMTimeStamp that measures the number of milliseconds from the point of the application's initialization. This could be used to store, update and track changes over a period of time since the last accelerometer update.

The following diagram shows the X, Y, and Z axis in relation to the device:

How it works…

The acceleration.x, acceleration.y, and acceleration.z values returned from the aforementioned acceleration object include the effect of gravity, which is defined as precisely 9.81 m/s^2.

Note

iOS doesn't know about the concept of getting current acceleration at any given point. Device motion must be watched and the data captured at a given time interval.

There's more...

Accelerometer data obtained from devices has been used to great effect in mobile handset games that require balance control and detection of movement, including steering, control views, and tilting objects. You can check out the official Cordova documentation covering the getCurrentAcceleration method and obtaining accelerometer data.

See also

主站蜘蛛池模板: 桑日县| 密山市| 义乌市| 达尔| 平邑县| 怀远县| 威宁| 梁平县| 通化县| 大姚县| 石首市| 常山县| 海丰县| 阿图什市| 清镇市| 两当县| 贵定县| 合肥市| 汉源县| 桦南县| 海口市| 大石桥市| 景泰县| 宝清县| 成都市| 大渡口区| 淮南市| 闽清县| 孟津县| 镇平县| 商水县| 安阳县| 安岳县| 大埔县| 毕节市| 柯坪县| 大厂| 邵阳县| 余江县| 秦皇岛市| 沙田区|