Android實現螢幕自動旋轉功能
阿新 • • 發佈:2019-01-25
最近在做一個視訊客戶端專案,有一個功能是,視訊要實現自動旋轉功能,在這裡做一簡單的總結。實現起來很簡單,幾行程式碼就能夠搞定。
直接看程式碼
1、繼承OrientationEventListener類監聽手機的旋轉
這裡用到的是OrientationEventListener類,它是當手機螢幕旋轉時從SensorManger接受通知的助手類。新建一個類繼承OrientationEventListener,如下
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) {
Log.d(TAG, "orention" + 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) {
Log.d(TAG, "設定豎屏" );
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
oriBtn.setText("豎屏");
}
} else if (orientation > 225 && orientation < 315) { //設定橫屏
Log.d(TAG, "設定橫屏");
if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
oriBtn.setText("橫屏");
}
} else if (orientation > 45 && orientation < 135) {// 設定反向橫屏
Log.d(TAG, "反向橫屏");
if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
oriBtn.setText("反向橫屏");
}
} else if (orientation > 135 && orientation < 225) {
Log.d(TAG, "反向豎屏");
if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
oriBtn.setText("反向豎屏");
}
}
}
}
2、在Activity中開啟自動旋轉
myOrientoinListener = new MyOrientoinListener(this);
boolean autoRotateOn = (android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1);
//檢查系統是否開啟自動旋轉
if (autoRotateOn) {
myOrientoinListener.enable();
}
3、Activity銷燬時在onDesotry裡取消監聽
@Override
protected void onDestroy() {
super.onDestroy();
//銷燬時取消監聽
myOrientoinListener.disable();
}
這樣就實現了螢幕自動旋轉的功能了,很簡單有木有!