关于OrientationEventListener监测指定的屏幕旋转角度,可以从自己的开发的场景不同进行使用;
不多说了,直接上代码;
public class MainActivity extends Activity {
OrientationEventListener mOrientationListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mOrientationListener = new OrientationEventListener(this,
SensorManager.SENSOR_DELAY_NORMAL) {
@Override
public void onOrientationChanged(int orientation) {
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
return; //手机平放时,检测不到有效的角度
}
//可以根据不同角度检测处理,这里只检测四个角度的改变
if (orientation > 350 || orientation < 10) { //0度
orientation = 0;
} else if (orientation > 80 && orientation < 100) { //90度
orientation = 90;
} else if (orientation > 170 && orientation < 190) { //180度
orientation = 180;
} else if (orientation > 260 && orientation < 280) { //270度
orientation = 270;
} else {
return;
}
}
};
if (mOrientationListener.canDetectOrientation()) {
mOrientationListener.enable();
} else {
mOrientationListener.disable();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mOrientationListener.disable();
}
}
源码分析:
构造方法
启动
关闭
核心代码
class SensorEventListenerImpl implements SensorEventListener {
private static final int _DATA_X = 0;
private static final int _DATA_Y = 1;
private static final int _DATA_Z = 2;
public void onSensorChanged(SensorEvent event) {
float[] values = event.values;
int orientation = ORIENTATION_UNKNOWN;
float X = -values[_DATA_X];
float Y = -values[_DATA_Y];
float Z = -values[_DATA_Z];
float magnitude = X*X + Y*Y;
// Don't trust the angle if the magnitude is small compared to the y value
if (magnitude * 4 >= Z*Z) {
float OneEightyOverPi = 57.29577957855f;
float angle = (float)Math.atan2(-Y, X) * OneEightyOverPi;
orientation = 90 - (int)Math.round(angle);
// normalize to 0 - 359 range
while (orientation >= 360) {
orientation -= 360;
}
while (orientation < 0) {
orientation += 360;
}
}
if (mOldListener != null) {
mOldListener.onSensorChanged(Sensor.TYPE_ACCELEROMETER, event.values);
}
if (orientation != mOrientation) {
mOrientation = orientation;
onOrientationChanged(orientation);
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}