Android通過重力感應監聽裝置方向改變
阿新 • • 發佈:2019-01-07
1.實現SensorEventListener
public class OrientationListener implements SensorEventListener { private int mOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; private OnOrientationChangeListener mListener; public OrientationListener(OnOrientationChangeListener listener) { mListener = listener; } @Override public void onSensorChanged(SensorEvent event) { if (Sensor.TYPE_ACCELEROMETER != event.sensor.getType()) { return; } float[] values = event.values; float x = values[0]; float y = values[1]; int newOrientation; if (x < 4.5 && x >= -4.5 && y >= 4.5) { newOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; } else if (x >= 4.5 && y < 4.5 && y >= -4.5) { newOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; } else if (x <= -4.5 && y < 4.5 && y >= -4.5) { newOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; }else { newOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; } if (mOrientation != newOrientation) { if (mListener != null) { mListener.orientationChanged(newOrientation); } mOrientation = newOrientation; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } public interface OnOrientationChangeListener { void orientationChanged(int newOrientation); } }
2.註冊Listener
private SensorManager mSensorManager; private OrientationListener mOrientationListener; private void init(){ mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE); mOrientationListener = new OrientationListener(newOrientation -> { //設定螢幕方向 //setRequestedOrientation(newOrientation); }); mSensorManager.registerListener(mOrientationListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); }
3.取消註冊
記得在onDestroy()中取消註冊的監聽
@Override
protected void onDestroy() {
super.onDestroy();
mSensorManager.unregisterListener(mOrientationListener);
}