Android的方向传感器存在一些Bug,因为Android设备中有些传感器并不是实实在在的硬件,而是由软件模拟的,这就导致了设备的方向并不总是准确的。要解决这个问题,可以通过代码获取设备的旋转角度(即设备朝向),然后进行屏幕的旋转。具体实现可以参考以下代码:
SensorManager mSensorManager;
SensorEventListener mSensorListener;
int mPreviousDegrees = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float degrees = Math.round(event.values[0]);
if (degrees != mPreviousDegrees) {
mPreviousDegrees = (int) degrees;
rotateScreen((int) degrees);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// unused
}
};
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR));
}
private void rotateScreen(int degrees) {
int orientation = getResources().getConfiguration().orientation;
int rotation = getWindowManager().getDefaultDisplay().getRotation();
if (((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && orientation == Configuration.ORIENTATION_PORTRAIT) ||
((rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && orientation == Configuration.ORIENTATION_LANDSCAPE)) {
degrees = -degrees;
}
setRequestedOrientation(degrees);
}
代码中的rotateScreen
方法会根据设备的旋转角度计算出