1. 程式人生 > >Android視訊播放器橫豎屏自動切換

Android視訊播放器橫豎屏自動切換

1、功能類

package com.tongyi.edu.util;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Message;

public class ScreenSwitchUtils {
    private volatile static ScreenSwitchUtils mInstance;
    private Activity mActivity;
    // 是否是豎屏
    private boolean isPortrait = true;
     
    private SensorManager sm;
    private OrientationSensorListener listener;
    private Sensor sensor;
 
    private SensorManager sm1;
    private Sensor sensor1;
    private OrientationSensorListener1 listener1;
     
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 888:
                int orientation = msg.arg1;
                if (orientation > 45 && orientation < 135) {
                	if (isPortrait) {
                        //切換成橫屏反向:ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
                		mActivity.setRequestedOrientation(8);
                		isPortrait = false;
                	}
                } else if (orientation > 135 && orientation < 225) {
                	if (!isPortrait) {
                        /*
                         * 切換成豎屏反向:ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT(9),
                         * ActivityInfo.SCREEN_ORIENTATION_SENSOR:根據重力感應自動旋轉
                         * 此處正常應該是上面第一個屬性,但是在真機測試時顯示為豎屏正向,所以用第二個替代
                         */
                		mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
                		isPortrait = true;
                	}
                } else if (orientation > 225 && orientation < 315) {
                    if (isPortrait) {
                        //切換成橫屏:ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                        mActivity.setRequestedOrientation(0);
                        isPortrait = false;
                    }
                } else if ((orientation > 315 && orientation < 360) || (orientation > 0 && orientation < 45)) {
                    if (!isPortrait) {
                        //切換成豎屏ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
                        mActivity.setRequestedOrientation(1);
                        isPortrait = true;
                    }
                }
                break;
            default:
                break;
            }
 
        };
    };
     
    /** 返回ScreenSwitchUtils單例 **/
    public static ScreenSwitchUtils init(Context context) {
        if (mInstance == null) {
            synchronized (ScreenSwitchUtils.class) {
                if (mInstance == null) {
                    mInstance = new ScreenSwitchUtils(context);
                }
            }
        }
        return mInstance;
    }
 
    private ScreenSwitchUtils(Context context) {
        // 註冊重力感應器,監聽螢幕旋轉
        sm = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        listener = new OrientationSensorListener(mHandler);
 
        // 根據 旋轉之後/點選全屏之後 兩者方向一致,啟用sm.
        sm1 = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        sensor1 = sm1.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        listener1 = new OrientationSensorListener1();
    }
     
    /** 開始監聽 */
    public void start(Activity activity) {
        mActivity = activity;
        sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);
    }
 
    /** 停止監聽 */
    public void stop() {
        sm.unregisterListener(listener);
        sm1.unregisterListener(listener1);
    }
     
    /**
     * 手動橫豎屏切換方向
     */
    public void toggleScreen() {
        sm.unregisterListener(listener);
        sm1.registerListener(listener1, sensor1,SensorManager.SENSOR_DELAY_UI);
        if (isPortrait) {
            isPortrait = false;
            // 切換成橫屏
            mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            isPortrait = true;
            // 切換成豎屏
            mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }
     
    public boolean isPortrait(){
        return this.isPortrait;
    }
    
    /**
     * 重力感應監聽者
     */
    public class OrientationSensorListener 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 rotateHandler;
 
        public OrientationSensorListener(Handler handler) {
            rotateHandler = 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
            // value
            if (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 range
                while (orientation >= 360) {
                    orientation -= 360;
                }
                while (orientation < 0) {
                    orientation += 360;
                }
            }
            if (rotateHandler != null) {
                rotateHandler.obtainMessage(888, orientation, 0).sendToTarget();
            }
        }
    }
 
    public class OrientationSensorListener1 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;
 
        public OrientationSensorListener1() {
        }
 
        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
            // value
            if (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 range
                while (orientation >= 360) {
                    orientation -= 360;
                }
                while (orientation < 0) {
                    orientation += 360;
                }
            }
            if (orientation > 225 && orientation < 315) {// 檢測到當前實際是橫屏
                if (!isPortrait) {
                    sm.registerListener(listener, sensor,SensorManager.SENSOR_DELAY_UI);
                    sm1.unregisterListener(listener1);
                }
            } else if ((orientation > 315 && orientation < 360) || (orientation > 0 && orientation < 45)) {// 檢測到當前實際是豎屏
                if (isPortrait) {
                    sm.registerListener(listener, sensor,SensorManager.SENSOR_DELAY_UI);
                    sm1.unregisterListener(listener1);
                }
            }
        }
    }
}
2、使用:
public class MainActivity extends Activity implements OnClickListener {
    private ScreenSwitchUtils instance;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = ScreenSwitchUtils.init(this.getApplicationContext());
    }
 
    @Override
    protected void onStart() {
        super.onStart();
        instance.start(this);
    }
 
    @Override
    protected void onStop() {
        super.onStop();
        instance.stop();
    }
 
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (instance.isPortrait()) {
            // 切換成豎屏
        } else {
            // 切換成橫屏
        }
    }
 
    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
        case R.id.iv_stretch:
            instance.toggleScreen();
            break;
        }
    }
}
附:
"unspecified" 預設值,由系統來選擇方向。它的使用策略,以及由於選擇時特定的上下文環境,可能會因為裝置的差異而不同。
"user" 使用使用者當前首選的方向。
"behind" 使用Activity堆疊中與該Activity之下的那個Activity的相同的方向。
"landscape" 橫向顯示(寬度比高度要大)
"portrait" 縱向顯示(高度比寬度要大)
"reverseLandscape" 與正常的橫向方向相反顯示,在API Level 9中被引入。
"reversePortrait" 與正常的縱向方向相反顯示,在API Level 9中被引入。
"sensorLandscape" 橫向顯示,但是基於裝置感測器,既可以是按正常方向顯示,也可以反向顯示,在API Level 9中被引入。
"sensorPortrait" 縱向顯示,但是基於裝置感測器,既可以是按正常方向顯示,也可以反向顯示,在API Level 9中被引入。
"sensor" 顯示的方向是由裝置的方向感測器來決定的。顯示方向依賴與使用者怎樣持有裝置;當用戶旋轉裝置時,顯示的方向會改變。但是,預設情況下,有些裝置不會在所有的四個方向上都旋轉,因此要允許在所有的四個方向上都能旋轉,就要使用fullSensor屬性值。
"fullSensor" 顯示的方向(4個方向)是由裝置的方向感測器來決定的,除了它允許螢幕有4個顯示方向之外,其他與設定為“sensor”時情況類似,不管什麼樣的裝置,通常都會這麼做。例如,某些裝置通常不使用縱向倒轉或橫向反轉,但是使用這個設定,還是會發生這樣的反轉。這個值在API Level 9中引入。
"nosensor" 螢幕的顯示方向不會參照物理方向感測器。感測器會被忽略,所以顯示不會因使用者移動裝置而旋轉。除了這個差別之外,系統會使用與“unspecified”設定相同的策略來旋轉螢幕的方向。