android 感應器擷取方向總結

來源:互聯網
上載者:User

在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);}}}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.