Detect accelerometer motion in android
Im working on an application which needs to detect accelerometer motion like shake or tilt the phone to right, left, up and down, based on these motions i'm sending some keys to my UPnP device.
for example if right motion is detected increase the volume of the media server and viceversa.
Please help me on this.
I have tried some example. it is working fine for Left and right. but i need a better solution for up and down.
here i add the code.
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
lastUpdate = System.currentTimeMillis();
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float[] values = event.values;
// Movement
float x = values[0];
float y = values[1];
float z = values[2];
/*float accelationSquareRoot = (x * x + y * y + z * z)
/ (SensorManager.AXIS_X * SensorManager.AXIS_X);*/
Log.d("Shakes","X: "+x+" Y: "+y+" Z: "+z);
long actualTime = System.currentTimeMillis();
if ((actualTime - lastUpdate) > 100)
{
long diffTime = (actualTime - lastUpdate);
lastUpdate = actualTime;
if(Round(x,4)>8.0000){
Log.d("sensor", "=====LEFT====");
}
else if(Round(x,4)<-8.0000){
Log.d("sensor", "=====RIGHT====");
}
else if(Ro开发者_如何学Pythonund(z,4) < -0.0){
Log.d("sensor", "=====UP====");
}
else if(Round(y,4) < 1.0){
Log.d("sensor", "=====DOWN====");
}
float speed = Math.abs(x+y+z - last_x - last_y - last_z) / diffTime * 10000;
if (speed > SHAKE_THRESHOLD) {
//Log.d("sensor", "shake detected w/ speed: " + speed);
//Toast.makeText(this, "shake detected w/ speed: " + speed, Toast.LENGTH_SHORT).show();
}
last_x = x;
last_y = y;
last_z = z;
}
}
}
The X axis is horizontal and points to the right, the Y axis is vertical and points up and the Z axis points towards the outside of the front face of the screen. In this system, coordinates behind the screen have negative Z values.
for more detail Android Developer
in your case try this.
if(Round(x,4)>8.0000){
Log.d("sensor", "=====LEFT====");
}
else if(Round(x,4)<-8.0000){
Log.d("sensor", "=====RIGHT====");
}
else if(Round(y,4) < 8.0){
Log.d("sensor", "=====UP====");
}
else if(Round(y,4) < -8.0){
Log.d("sensor", "=====DOWN====");
}
if(Round(x,4)>8.0000){
Log.d("sensor", "=====LEFT====");
}
else if(Round(x,4)<-8.0000){
Log.d("sensor", "=====RIGHT====");
}
else if (z >9 && z < 10)
Log.d("sensor", "=====DOWN====");
else if (z > -10 && z < -9)
Log.d("sensor", "=====UP====");
精彩评论