Thursday, January 29, 2015

PhoneGap plugins: Accelerometer


For Accelerometer plugin you need to install device-motion plugin, as here

phonegap plugin add org.apache.cordova.device-motion

For Android nothing is needed to add into AndroidManifest.xml file.
For iOS you need to add into config.xml file:


<plugin name="Accelerometer" value="CDVAccelerometer" />


Here is some html and javascipt code to run a quickly example.


<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">

    document.addEventListener("deviceready", onDeviceReady, false);
   
    function onDeviceReady() {
        alert("Device is Ready");
    }

    function getAcceleration(){
        navigator.accelerometer.getCurrentAcceleration(onAccelSuccess, onError);
    }

    function onAccelSuccess(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 />';
    }

    function onError() {
        alert('onError!');
    }

    function startWatch() {
        // Update acceleration every 1 seconds
        var options = { frequency: 1000 };

        watchID = navigator.accelerometer.watchAcceleration(onAccelSuccess, onError, options);
    }

    function stopWatch() {
        if (watchID) {
            navigator.accelerometer.clearWatch(watchID);
            watchID = null;
        }
    }
    </script>



And here the html code....

 <body>
    <h1>PhoneGap Accelerometer Example</h1>
    <p>
        <button onclick="getAcceleration()">Get Acceleration</button>
    </p>
    <p>
        <button onclick="startWatch()">Start Acceleration Debug</button>
    </p>
    <p>
        <button onclick="stopWatch()">Stop Acceleration Debug</button>
    </p>
    <div id="accelerometer">Accelerometer debug area...</div>
  </body>


This html code shows three buttons.
Two of them invoke the two javascript functions getAcceleration() and startWatch().
The results is displayed into div area with id="accelerometer", in the lower of the page.

Bye...

No comments:

Post a Comment