Accelerometer

The accelerometer plugin provides access to the device's accelerometer in order to get the delta in movement relative to the current device's orientation in the x, y, and z axes.

In order to use the accelerometer in our Apache Cordova project, we need to use the following cordova plugin add command:

> cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-device-motion.git

Demo

In order to access the accelerometer demo, you need to click on the accelerometer list item. You will be introduced to the Accelerometer page. You can then click on the Start Watch Acceleration button in order to start watching the accelerometer. You will then be able to get the acceleration information in the x, y, and z axes, as shown in the following screenshot:

Demo

The Accelerometer page in action

You can click on the Stop Watch Acceleration button to stop watching the accelerometer at any time.

The HTML page

The following code snippet shows the "accelerometer" page:

<div data-role="page" id="accelerometer"> 
    <div data-role="header">
        <h1>Accelerometer</h1>
        <a href="#" data-role="button" data-rel="back" data-icon="back">Back</a>
    </div>
    <div data-role="content">
        <h1>Welcome to the Accelerometer Gallery</h1>
        <p>Click 'Start Watch Acceleration' button below to start watch acceleration.</p>
        <input type="button" id="startWatchAcceleration" value="Start Watch Acceleration"/>
        <input type="button" id="stopWatchAcceleration" value="Stop Watch Acceleration"/>
        <div id="acceleration">
        </div>
    </div>
</div>

As shown in the preceding "accelerometer" page code snippet, it contains the following:

  • A page header that includes a back button
  • Page content that includes the following main elements:
    • "startWatchAcceleration": This button is used to start watching acceleration
    • "stopWatchAcceleration": This button is used to stop watching acceleration
    • "acceleration": This div is used to display the acceleration result

View controller

The following code snippet shows the page view controller JavaScript object, which includes the event handlers of the page (accelerometer.js):

(function() {
    var accelerometerManager = AccelerometerManager.getInstance();
    var watchID;

    $(document).on("pageinit", "#accelerometer", function(e) {
        e.preventDefault();

        $("#startWatchAcceleration").on("tap", function(e) {
            e.preventDefault();

            enableStartWatchAccelerationButton(false); 

            var callback = {};

            callback.onSuccess = onSuccess;
            callback.onError = onError;

            watchID = accelerometerManager.startWatchAcceleration(callback);
        });       

        $("#stopWatchAcceleration").on("tap", function(e) {
            e.preventDefault();

            enableStartWatchAccelerationButton(true);

            accelerometerManager.stopWatchAcceleration(watchID);
        });

        initPage();
    });

    $(document).on("pagebeforehide", "#accelerometer", function(e) {        
        accelerometerManager.stopWatchAcceleration(watchID);
        enableStartWatchAccelerationButton(true);
    });    

    function initPage() {
        $("#stopWatchAcceleration").closest('.ui-btn').hide();
    }
    function onSuccess(acceleration) {
        $("#acceleration").html("Acceleration X: " + acceleration.x + "<br/>" +
          "Acceleration Y: " + acceleration.y + "<br/>" +
          "Acceleration Z: " + acceleration.z + "<br/>" +
          "Timestamp: "      + acceleration.timestamp + "<br/>");    
    }

    function onError() {
        $("#acceleration").html("An error occurs during watching acceleration.");
    }  

    function enableStartWatchAccelerationButton(enable) {
        if (enable) {
            $("#startWatchAcceleration").button("enable");
            $("#stopWatchAcceleration").closest('.ui-btn').hide(); 
        } else {
            $("#startWatchAcceleration").button("disable");
            $("#stopWatchAcceleration").closest('.ui-btn').show(); 
        }

        $("#startWatchAcceleration").button("refresh");
    }

})();

The "pageinit" event handler, which is called once in the page initialization, registers the "startWatchAcceleration" tap event handler. The "startWatchAcceleration" tap event handler does the following:

  • It disables the "startWatchAcceleration" button and shows the "stopWatchAcceleration" button by calling enableStartWatchAccelerationButton(false)
  • It starts watching the acceleration by calling accelerometerManager.startWatchAcceleration(callback), specifying a callback object that contains the following:
    • The onSuccess callback that will be called if the operation succeeds
    • The onError callback that will be called if the operation fails

The accelerometerManager.startWatchAcceleration(callback) function returns watchID, which will be used in order to stop watching the acceleration.

The "pageinit" event handler, which is called once in the page initialization, registers the "stopWatchAcceleration" tap event handler. The "stopWatchAcceleration" tap event handler does the following:

  • It hides the "stopWatchAcceleration" button and enables the "startWatchAcceleration" button by calling enableStartWatchAccelerationButton(true)
  • It stops watching the acceleration by calling accelerometerManager.stopWatchAcceleration(watchID) and specifying watchID, which we get from the accelerometerManager.startWatchAcceleration(callback) call

The "pageinit" event handler also calls initPage() in order to hide the "stopWatchAcceleration" button at the beginning. In onSuccess(acceleration), which will be called if accelerometerManager.startWatchAcceleration(callback) succeeds, the x, y, and z acceleration is shown with the current timestamp. In onError(), which will be called if accelerometerManager.startWatchAcceleration(callback) fails, an error message is displayed.

Finally, in order to stop watching acceleration before leaving the page, accelerometerManager.stopWatchAcceleration() is called in the "pagebeforehide" event, which will be called every time we transition away from the page.

API

The following code snippet shows the accelerometer manager JavaScript object that interacts with the Apache Cordova Accelerometer API (AccelerometerManager.js). Note that the manager files are always included in the index.html file before the view controller files so that the manager objects can be used by view controller objects:

var AccelerometerManager = (function () {     
  var instance;

  function createObject() {
      return {
          startWatchAcceleration: function (callback) {
              return navigator.accelerometer.watchAcceleration(callback.onSuccess,
callback.onError,
{frequency: 2000});
          },
          stopWatchAcceleration: function (watchID) {    
              if (watchID) {
                  navigator.accelerometer.clearWatch(watchID);
              }
          }
      };
  };

  return {
    getInstance: function () {
      if (!instance) {
          instance = createObject();
      }

      return instance;
    }
  }; 
})();

As you can see, AccelerometerManager is a singleton object that has the following two methods, as highlighted in the preceding code:

  • startWatchAcceleration(callback): This uses the Cordova navigator.accelerometer.watchAcceleration() method to watch acceleration. The navigator.accelerometer.watchAcceleration(accelerometerSuccess, accelerometerError,[accelerometerOptions]) method has the following parameters:
    • accelerometerSuccess: This will be called if the operation succeeds with an object that contains the current acceleration along the x, y, and z axes and the timestamp. In AccelerometerManager, accelerometerSuccess is set to callback.onSuccess.
    • accelerometerError: This will be called if the operation fails. In AccelerometerManager, accelerometerError is set to callback.onError.
    • accelerometerOptions: This is an optional parameter that holds the accelerometer's configuration. It has a frequency attribute to specify how often to retrieve acceleration in milliseconds. In AccelerometerManager, the frequency parameter is set to 2000 milliseconds (note that this parameter is 10000 milliseconds by default).
  • stopWatchAcceleration(watchID): This uses the Cordova navigator.accelerometer.clearWatch() method to remove watching acceleration. navigator.accelerometer.clearWatch(watchID) has the following parameter:
    • watchID: This represents the ID returned by navigator.accelerometer.watchAcceleration().

We are now done with the Accelerometer functionality in our Cordova Exhibition app. However, before exploring the Camera functionality, note that the navigator.accelerometer object has also the method shown in the following table:

Method name

Description

navigator.accelerometer.getCurrentAcceleration

(accelerometerSuccess, accelerometerError)

This method retrieves the current acceleration along the x, y, and z axes. Acceleration values are returned to the accelerometerSuccess callback function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.170.223