Search code examples
javascriptcordovacordova-plugins

Cordova Accelerometer Plugin Watch Acceleration Issue


I've been experimenting with Cordova's Accelerometer Plugin and have an issue that so far I've been unable to fix on Android. motionID is used within the clearWatch method to halt watchAcceleration.

More info can be found here cordova-plugin-device-motion docs

var motionID = null;


function startAccelerometer() {
var refreshRate = {
    frequency: 50
};
motionID = navigator.accelerometer.watchAcceleration(
    gotMotion, onMotionError, refreshRate);
}

Then using the clearWatch() function to stop it I call

function stopAcclererometer() {

navigator.accelerometer.clearWatch(motionID);
$("#acclData").empty();
}

The problem seem to be that clearWatch does not clear the motionID if startAccelerometer() is called more than once, or if a new motionID is created without first clearing it.

Any help is greatly appreciated.


Solution

  • It was a fairly simple fix but I'm still wondering if there may be a cleaner way to solve the problem. I managed to get around it by attaching a simple count into the mix and exiting if a condition has been reached i.e. Start was pressed and then clearing the count when Stopped.

    if (count > 0) {
            return;
        } else if (count === 0) {
            startAccelerometer();
        }
    });