android – 使用传感器事件检测手机方向
时间:2023-12-03 10:37:02
听起来你需要代码来改变设备的方向,而不是每个角度的反应.方向过滤为0度、90度、180度和270度:
OrientationEventListener myOrientationEventListener;
int iOrientation;
myOrientationEventListener = new OrientationEventListener(this,SensorManager.SENSOR_DELAY_NORMAL)
{
@Override
public void onOrientationChanged(int iAngle)
{ // 0 15 30 45 60 75,90 105、120、135、150、165、180、195、225、240、25、270、285、300、315、330
final int iLookup[] = {0,90,0}; // 15-degree increments
if (iAngle != ORIENTATION_UNKNOWN)
{
int iNewOrientation = iLookup[iAngle / 15];
if (iOrientation != iNewOrientation)
{
iOrientation = iNewOrientation;
// take action on new orientation here
}
}
}
};
// To display if orientation detection will work and enable it
if (myOrientationEventListener.canDetectOrientation())
{
Toast.makeText(this,"Can DetectOrientation",Toast.LENGTH_LONG).show();
myOrientationEventListener.enable();
}
else
{
Toast.makeText(this,"Can't DetectOrientation",Toast.LENGTH_LONG).show();
}