onSensorChanged 检查手机是否处于水平位置(无横向)

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

我需要检查手机是否处于水平位置(没有横向,我的意思是你把它放在 table 上)。

我知道我必须使用 "SensorEventListener" 界面和 "onSensorChanged" 事件,但我无法获得如何检查移动位置的示例。

@Override
public void onSensorChanged(SensorEvent event) {
    //
}

试试这个:

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