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

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

主站蜘蛛池模板: 聂拉木县| 沅陵县| 汪清县| 牡丹江市| 芦山县| 余庆县| 平阳县| 武威市| 怀集县| 丰城市| 罗江县| 略阳县| 酒泉市| 阜新| 万山特区| 普宁市| 崇仁县| 平湖市| 高陵县| 韶山市| 益阳市| 大足县| 韶山市| 张北县| 皋兰县| 仁布县| 洛南县| 庐江县| 阜康市| 射洪县| 芷江| 汉源县| 宝应县| 溧阳市| 同心县| 庆元县| 洛扎县| 招远市| 古浪县| 盐池县| 吴桥县|