Reputation: 4723
I need to check if the mobile goes to the horizontal position (no landscape, I mean like you place it on the table).
I know I have to use "SensorEventListener" interface and the "onSensorChanged" event, but I am not able to get an example to howto check the mobile position.
@Override
public void onSensorChanged(SensorEvent event) {
//
}
Upvotes: 2
Views: 206
Reputation: 1948
Try this:
@Override
public void onSensorChanged(SensorEvent event) {
float[] values = event.values;
float x = values[0];
float y = values[1];
float z = values[2];
float norm =(float) Math.sqrt(x * x + y * y + z * z);
// Normalize the accelerometer vector
x = (x / norm);
y = (y / norm);
z = (z / norm);
int inclination = (int) Math.round(Math.toDegrees(Math.acos(z)));
if (inclination < 25 || inclination > 155)
{
// device is horiontal
Toast.makeText(this,"device horiontal !",Toast.LENGTH_SHORT).show();
}
}
Upvotes: 3