public class MainActivity extends AppCompatActivity { private MyOrientoinListener myOrientoinListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myOrientoinListener = new MyOrientoinListener(this); boolean autoRotateOn = (android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1); //檢查系統是否開啓自動旋轉 if (autoRotateOn) { myOrientoinListener.enable(); } } @Override protected void onDestroy() { super.onDestroy(); //銷燬時取消監聽 myOrientoinListener.disable(); } class MyOrientoinListener extends OrientationEventListener { public MyOrientoinListener(Context context) { super(context); } public MyOrientoinListener(Context context, int rate) { super(context, rate); } @Override public void onOrientationChanged(int orientation) { int screenOrientation = getResources().getConfiguration().orientation; if (((orientation >= 0) && (orientation < 45)) || (orientation > 315)) { //設置豎屏 if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT && orientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } else if (orientation > 225 && orientation < 315) { //設置橫屏 if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } } else if (orientation > 45 && orientation < 135) {// 設置反向橫屏 if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE); } } else if (orientation > 135 && orientation < 225) { //反向豎屏 if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT); } } } }