實時獲取當前螢幕方向
阿新 • • 發佈:2018-11-04
背景
開發中,有時需要獲取當前螢幕的方向,所以單獨寫了個demo,方便大家參考。
效果:
Demo原始碼:
https://gitee.com/cxyzy1/screenOrientation.git
主要程式碼:
public class MainActivity extends AppCompatActivity { private final String TAG = MainActivity.class.getSimpleName(); private CameraOrientationListener orientationListener; private TextView txt; /** * 當前螢幕旋轉角度 */ private int mOrientation = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txt = findViewById(R.id.textView); orientationListener = new CameraOrientationListener(this); orientationListener.enable(); startOrientationChangeListener(); } /** * 啟動螢幕朝向改變監聽函式 用於在螢幕橫豎屏切換時改變儲存的圖片的方向 */ private void startOrientationChangeListener() { OrientationEventListener mOrEventListener = new OrientationEventListener(this) { @Override public void onOrientationChanged(int rotation) { Log.i(TAG, "當前螢幕手持角度方法:" + rotation + "°"); if (((rotation >= 0) && (rotation <= 45)) || (rotation > 315)) { rotation = 0; } else if ((rotation > 45) && (rotation <= 135)) { rotation = 90; } else if ((rotation > 135) && (rotation <= 225)) { rotation = 180; } else if ((rotation > 225) && (rotation <= 315)) { rotation = 270; } else { rotation = 0; } if (rotation == mOrientation) { return; } mOrientation = rotation; } }; mOrEventListener.enable(); } /** * 當方向改變時,將呼叫偵聽器onOrientationChanged(int) */ private class CameraOrientationListener extends OrientationEventListener { private int mCurrentNormalizedOrientation; public CameraOrientationListener(Context context) { super(context, SensorManager.SENSOR_DELAY_NORMAL); } @Override public void onOrientationChanged(final int orientation) { Log.i(TAG, "當前螢幕手持角度:" + orientation + "°"); if (orientation != ORIENTATION_UNKNOWN) { mCurrentNormalizedOrientation = normalize(orientation); } runOnUiThread(new Runnable() { @Override public void run() { String str = "當前螢幕手持角度:" + orientation + "°\n當前螢幕手持方向:" + mCurrentNormalizedOrientation; txt.setText(str); } }); } private int normalize(int degrees) { if (degrees > 315 || degrees <= 45) { return 0; } if (degrees > 45 && degrees <= 135) { return 90; } if (degrees > 135 && degrees <= 225) { return 180; } if (degrees > 225 && degrees <= 315) { return 270; } throw new RuntimeException("The physics as we know them are no more. Watch out for anomalies."); } } }
Manifest檔案中配置activity時,需要配置:
android:configChanges="orientation|screenSize"