在2.2中可以設定螢幕的方向為反轉橫屏:setRequestedOrientation(8);,因為系統沒有公開出這個參數的設定,不過在源碼裡面已經定義了SCREEN_ORIENTATION_REVERSE_LANDSCAPE這個參數,但是無法固定螢幕的方向為反轉橫屏即右橫屏。在設定螢幕方向為右橫屏的時候 還得注意一點,需要將activity設定為android:theme="@android:style/Theme.Translucent",否則即使設定了setRequestedOrientation(8);也不會顯示為右橫屏。
雖然能根據旋轉角度擷取到螢幕的方向,但是在2.1的時候根本無法設定為右橫屏,下面記錄一點從源碼摳出來的根據感應器根據角度擷取螢幕方向。
感應器監聽:
class SubSensorListener implements SensorEventListener {private static final int _DATA_X = 0;private static final int _DATA_Y = 1;private static final int _DATA_Z = 2;public static final int ORIENTATION_UNKNOWN = -1;private Handler handler;public SubSensorListener (Handler handler) {this.handler = handler;}public void onAccuracyChanged(Sensor arg0, int arg1) {}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 valueif (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 rangewhile (orientation >= 360) {orientation -= 360;}while (orientation < 0) {orientation += 360;}}if (handler != null) {handler.obtainMessage(123, orientation, 0).sendToTarget();}}
由於方向的改變會不斷髮生變化,所以我們需要一個handler來處理,下面是handler通過對旋轉角度的處理獲得方向:
@Overridepublic void handleMessage(Message msg) {if (msg.what == 123) {int orientation = msg.arg1;if (orientation > 45 && orientation < 135) {// SCREEN_ORIENTATION_REVERSE_LANDSCAPEactivity.setRequestedOrientation(8);} else if (orientation > 135 && orientation < 225) {// SCREEN_ORIENTATION_REVERSE_PORTRAITactivity.setRequestedOrientation(9);} else if (orientation > 225 && orientation < 315) {// SCREEN_ORIENTATION_LANDSCAPEactivity.setRequestedOrientation(0);} else if ((orientation > 315 && orientation < 360) || (orientation > 0 && orientation < 45)) {// SCREEN_ORIENTATION_PORTRAITactivity.setRequestedOrientation(1);}}}