有没有办法检测Android设备的当前方向?
我不是在谈论屏幕方向,而是在谈论设备的物理放置方式。到目前为止,我找到的所有解决方案都告诉我屏幕方向(在我的应用程序中始终为纵向)。我需要知道即使我没有旋转屏幕,用户是否也要水平握住设备。
谢谢。
您可以使用加速度计。要使用它,您需要在传感器TYPE_ACCELEROMETER上注册一个监听器。
完成后,您将在此传感器的值发生变化时收到通知(当用户将设备握在手中时,这种情况非常频繁)。
从该传感器接收到的值是(代表)重力在 X、Y 和 Z 轴上的投影。(嗯……这并不完全正确:事实上,这些值代表了施加到设备上的所有力的总和的投影)所以:
SensorEvent.values[0]) :表示设备的右边缘如果在左边缘下方。SensorEvent.values[1]) :表示顶边在底边之下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)
| 归档时间: |
|
| 查看次数: |
952 次 |
| 最近记录: |