Cordova - Accelerometer
Cordova - Accelerometer (Device Motion)
Section titled “Cordova - Accelerometer (Device Motion)”The Apache Cordova Device Motion plugin (historically known as Accelerometer plugin) provides access to the device’s accelerometer. The accelerometer is a motion sensor that detects the change (delta) in movement relative to the current device orientation, in three dimensions along the x, y, and z axis.
This plugin provides the navigator.accelerometer object with methods to get the current acceleration and watch for changes in acceleration.
Step 1 - Install Device Motion Plugin
Section titled “Step 1 - Install Device Motion Plugin”Install the plugin using the Cordova CLI. Ensure you are in your project’s root directory.
cordova plugin add cordova-plugin-device-motionAlways ensure your project is built after adding a plugin: cordova build <platform> (e.g., cordova build android).
Step 2 - Prepare the UI
Section titled “Step 2 - Prepare the UI”In your www/index.html file, add buttons to trigger accelerometer actions and a placeholder to display the data. This makes it easier to see the results than using alert().
<body> <h1>Accelerometer Demo</h1> <button id="getAccelerationBtn">GET CURRENT ACCELERATION</button> <button id="watchAccelerationBtn">START WATCHING ACCELERATION</button> <button id="stopWatchAccelerationBtn">STOP WATCHING ACCELERATION</button> <div id="accelerometerData"> <p>X: <span id="accelX">N/A</span></p> <p>Y: <span id="accelY">N/A</span></p> <p>Z: <span id="accelZ">N/A</span></p> <p>Timestamp: <span id="accelTimestamp">N/A</span></p> </div> <script src="cordova.js"></script> <script src="js/index.js"></script></body>Step 3 - Implement JavaScript Logic
Section titled “Step 3 - Implement JavaScript Logic”In your www/js/index.js file, within the onDeviceReady function, add event listeners and implement the functions to interact with the accelerometer. Remember, Cordova plugin APIs are only available after the deviceready event.
document.addEventListener('deviceready', onDeviceReady, false);
let watchID = null;
function onDeviceReady() { console.log('Device is ready.'); document.getElementById('getAccelerationBtn').addEventListener('click', getCurrentAcceleration); document.getElementById('watchAccelerationBtn').addEventListener('click', startWatchAcceleration); document.getElementById('stopWatchAccelerationBtn').addEventListener('click', stopWatchAcceleration);}
function updateAccelerationUI(acceleration) { document.getElementById('accelX').textContent = acceleration.x.toFixed(2); document.getElementById('accelY').textContent = acceleration.y.toFixed(2); document.getElementById('accelZ').textContent = acceleration.z.toFixed(2); document.getElementById('accelTimestamp').textContent = new Date(acceleration.timestamp).toLocaleTimeString();}
function accelerometerError(error) { console.error('Accelerometer Error: ', error); alert('Accelerometer Error: ' + (error.message || 'Unknown error'));}
// Get current accelerationfunction getCurrentAcceleration() { navigator.accelerometer.getCurrentAcceleration(updateAccelerationUI, accelerometerError);}
// Start watching accelerationfunction startWatchAcceleration() { if (watchID) { // Already watching console.log('Already watching acceleration.'); return; } const options = { frequency: 1000 }; // Update every 1 second (1000 ms) watchID = navigator.accelerometer.watchAcceleration( (acceleration) => { console.log('Watching acceleration:', acceleration); updateAccelerationUI(acceleration); }, accelerometerError, options ); console.log('Started watching acceleration with watchID: ' + watchID); document.getElementById('watchAccelerationBtn').disabled = true; document.getElementById('stopWatchAccelerationBtn').disabled = false;}
// Stop watching accelerationfunction stopWatchAcceleration() { if (watchID) { navigator.accelerometer.clearWatch(watchID); watchID = null; console.log('Stopped watching acceleration.'); document.getElementById('watchAccelerationBtn').disabled = false; document.getElementById('stopWatchAccelerationBtn').disabled = true; } else { console.log('Not currently watching acceleration.'); }}Understanding the Output
Section titled “Understanding the Output”The acceleration values (x, y, z) are given in m/s^2 and include the force of gravity. For example, a device lying flat on a table will show approximately +9.81 m/s^2 for one of the axes.
- x: Acceleration on the x-axis.
- y: Acceleration on the y-axis.
- z: Acceleration on the z-axis.
- timestamp: Creation timestamp in milliseconds.
Practical Applications
Section titled “Practical Applications”The accelerometer can be used for:
- Gesture Detection: Detecting shakes, tilts, or specific device movements.
- Gaming: Controlling characters or game elements through device motion.
- Orientation Detection: Supplementing orientation data, though
Screen Orientationplugin orwindow.orientationmight be more direct for simple screen rotation. - Health and Fitness Apps: Pedometer-like functionality (though dedicated step counter APIs are often more accurate).
Common Pitfalls & Best Practices
Section titled “Common Pitfalls & Best Practices”devicereadyEvent: Always ensurenavigator.accelerometercalls are made after thedevicereadyevent has fired.- Error Handling: Implement the
onErrorcallback to manage situations where the accelerometer might not be available or an error occurs. - Frequency: Be mindful of the
frequencyoption inwatchAcceleration. High frequencies can consume more battery. Choose a rate appropriate for your application’s needs. - Clearing Watchers: Always call
clearWatchwhen you no longer need to monitor acceleration (e.g., when the user navigates away from the feature or the app is paused) to save battery. The example above shows manual stop, but you might also hook intopauseevent. - Permissions: While generally not requiring explicit user permission prompts like Camera or Geolocation, access can still be restricted by device policies on some platforms or in specific contexts.
For more detailed information, refer to the official documentation: Cordova Device Motion Plugin.