標籤:
最近在處理相機拍照的方向問題,在Android Device的Orientation問題上有了些疑問,就順便寫個Demo瞭解下Android Device Orientation究竟是怎麼個判斷。
Android Device Orientation的使用情境其實最常見的就是視頻播放軟體了,它會隨著你擺弄手機的方向,來調整一個最適合的畫面旋轉讓使用者觀看。官方API文檔裡對Android Device Orientation有這麼一句話:
public abstract void onOrientationChanged (int orientation)添加於 API 層級 3
Called when the orientation of the device has changed. orientation parameter is in degrees, ranging from 0 to 359. orientation is 0 degrees when the device is oriented in its natural position, 90 degrees when its left side is at the top, 180 degrees when it is upside down, and 270 degrees when its right side is to the top. ORIENTATION_UNKNOWN is returned when the device is close to flat and the orientation cannot be determined.
對於這句話,有一點不理解的就是natural position到底是一個什麼個position,其實就是我們正常用手機的擺放方向,如:Orientation為0
Left Side Top, Orientation為90:
Right Side Top, Orientation為270:
Top Side Down,Orientation為180
好了,差不多就是這樣了。再放上一次我測試時用的代碼:
1 public class MainActivity extends ActionBarActivity { 2 3 4 private TextView textView = null; 5 private MyOrientationListener myOrientationListener = null; 6 @Override 7 protected void onCreate(Bundle savedInstanceState) { 8 super.onCreate(savedInstanceState); 9 setContentView(R.layout.activity_main);10 textView = (TextView)findViewById(R.id.textview);11 myOrientationListener = new MyOrientationListener(this, SensorManager.SENSOR_DELAY_NORMAL);12 if( myOrientationListener.canDetectOrientation()){13 myOrientationListener.enable();14 }15 else{16 Toast.makeText(this, "Can‘t Detect Orientation", Toast.LENGTH_LONG).show();17 }18 19 }20 21 @Override22 public boolean onCreateOptionsMenu(Menu menu) {23 // Inflate the menu; this adds items to the action bar if it is present.24 getMenuInflater().inflate(R.menu.main, menu);25 return true;26 }27 28 @Override29 protected void onDestroy(){30 super.onDestroy();31 myOrientationListener.disable();32 }33 34 @Override35 protected void onResume(){36 super.onResume();37 if( myOrientationListener.canDetectOrientation()){38 myOrientationListener.enable();39 }40 else{41 Toast.makeText(this, "Can‘t Detect Orientation", Toast.LENGTH_LONG).show();42 }43 }44 45 @Override46 public boolean onOptionsItemSelected(MenuItem item) {47 // Handle action bar item clicks here. The action bar will48 // automatically handle clicks on the Home/Up button, so long49 // as you specify a parent activity in AndroidManifest.xml.50 int id = item.getItemId();51 if (id == R.id.action_settings) {52 return true;53 }54 return super.onOptionsItemSelected(item);55 }56 57 58 private class MyOrientationListener extends OrientationEventListener{59 60 public MyOrientationListener(Context context, int rate) {61 super(context, rate);62 // TODO Auto-generated constructor stub63 }64 65 @Override66 public void onOrientationChanged(int orientation) {67 // TODO Auto-generated method stub68 textView.setText("" + orientation);69 }70 71 72 73 }74 }View Code
Android Device Orientation