检测Android设备方向(不是屏幕方向)

use*_*238 5 android

有没有办法检测Android设备的当前方向?

我不是在谈论屏幕方向,而是在谈论设备的物理放置方式。到目前为止,我找到的所有解决方案都告诉我屏幕方向(在我的应用程序中始终为纵向)。我需要知道即使我没有旋转屏幕,用户是否也要水平握住设备。

谢谢。

ben*_*n75 5

您可以使用加速度计。要使用它,您需要在传感器TYPE_ACCELEROMETER上注册一个监听器。

完成后,您将在此传感器的值发生变化时收到通知(当用户将设备握在手中时,这种情况非常频繁)。

从该传感器接收到的值是(代表)重力在 X、Y 和 Z 轴上的投影。(嗯……这并不完全正确:事实上,这些值代表了施加到设备上的所有力的总和的投影)所以:

  • X 轴上的正值 ( SensorEvent.values[0]) :表示设备的右边缘如果在左边缘下方。
  • Y 轴上的正值 ( SensorEvent.values[1]) :表示顶边在底边之下
  • Z 轴上的正值 ( SensorEvent.values[2]) :表示设备正面如果面向地面,因此必须颠倒前 2 条规则。

这是示例代码(警告:它不关心 Z 轴上的值)

/**
 *  Logs the device orientation. Results are not valid when the screen is facing the ground.
 *  (when the discriminant value is low (i.e. device almost horizontal) : no logs)
 */
public void onSensorChanged(SensorEvent event) {
    if (event.sensor == mAccelerometer) {
        if(Math.abs(event.values[1]) > Math.abs(event.values[0])) {
            //Mainly portrait
            if (event.values[1] > 1) {
                Log.d(TAG,"Portrait");
            } else if (event.values[1] < -1) {
                Log.d(TAG,"Inverse portrait");
            }
        }else{
            //Mainly landscape
            if (event.values[0] > 1) {
                Log.d(TAG,"Landscape - right side up");
            } else if (event.values[0] < -1) {
                Log.d(TAG,"Landscape - left side up");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)