Reputation: 649
I'm trying to detect shaking event using Cordova 2.2.0 for android devices. I found some question related to this topic but t's in native code for example this question and this question.
Does anyone knows how to detect this event using phonegap Cordova ? or I should write a plugin ?
Upvotes: 6
Views: 7250
Reputation: 152085
Cordova offers the device-motion plugin, which (surprisingly) exposes a navigator.accelerometer
object, instead of aligning with the W3C deviceorientation/devicemotion standard published since 2011.
When the device lays flat on a surface, the (x, y, z) acceleration will be (0, 0, 9.81). The basic idea for detecting a shake is to watch the acceleration with a given frequency, calculate the delta from the previous sample, and decide if it's larger than a threshold.
navigator.accelerometer.watchAcceleration(onSuccess, onError, { frequency: 300 });
// Assess the current acceleration parameters to determine a shake
function onSuccess(acceleration) {
var accelerationChange = {};
if (previousAcceleration.x !== null) {
accelerationChange.x = Math.abs(previousAcceleration.x - acceleration.x);
accelerationChange.y = Math.abs(previousAcceleration.y - acceleration.y);
accelerationChange.z = Math.abs(previousAcceleration.z - acceleration.z);
}
previousAcceleration = {
x: acceleration.x,
y: acceleration.y,
z: acceleration.z
};
if (accelerationChange.x + accelerationChange.y + accelerationChange.z > sensitivity) {
// Shake detected, invoke callback
}
}
A plugin doing that is Lee Crossley's cordova-plugin-shake-detection.
Upvotes: 0
Reputation: 1869
Use the accelerometer to store the previous values (x, y and z). Defining the thresholds (x,y,z) you can detect shaking if the different betwen the previosValues and the actual once (event.value[i] where i=x,y ans z) is higher than the thresholds.
You also can use the magnitude of the acceleration values (Acc=sqrt(x*x+y*y+z*z)) or the timestamp to obtain better results.
Upvotes: 2