Search code examples
androidandroid-sensors

onSensorChanged check if the mobile is in an horizontal position (no landscape)


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) {
    //
}

Solution

  • 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();
        }
    }