在播放视频的时候,可能要做横竖屏的切换,但是,用户可以设置自己的手机关掉屏幕旋转,这个时候就需要想其他的办法了,比如:加速传感器或者OrientationEventListener。

1、这是用加速传感器来实现:

public class ScreenSwitchUtils {private static final String TAG = ScreenSwitchUtils.class.getSimpleName();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) {} else if (orientation > 135 && orientation < 225) {} else if (orientation > 225 && orientation < 315) {if (isPortrait) {Log.e("test", "切换成横屏");mActivity.setRequestedOrientation(0);isPortrait = false;}} else if ((orientation > 315 && orientation < 360) || (orientation > 0 && orientation < 45)) {if (!isPortrait) {Log.e("test","切换成竖屏");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) {Log.d(TAG, "init orientation listener.");// 注册重力感应器,监听屏幕旋转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) {Log.d(TAG, "start orientation listener.");mActivity = activity;sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);}/** 停止监听 */public void stop() {Log.d(TAG, "stop orientation listener.");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// 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 (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// 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 (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);}}}}
}

转载请标明出处:http://blog.csdn.net/goldenfish1919/article/details/47423131

使用的时候:

public class MainActivity extends Activity implements OnClickListener {private ScreenSwitchUtils instance;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);instance = ScreenSwitchUtils.init(this.getApplicationContext());}@Overrideprotected void onStart() {super.onStart();instance.start(this);}@Overrideprotected void onStop() {super.onStop();instance.stop();}@SuppressLint("NewApi")@Overridepublic void onConfigurationChanged(Configuration newConfig) {super.onConfigurationChanged(newConfig);Log.e("test", "onConfigurationChanged");if (instance.isPortrait()) {// 切换成竖屏LayoutParams params1 = new RelativeLayout.LayoutParams(screenWidth, DensityUtil.dip2px(this, 160));videoView.setLayoutParams(params1);Toast.makeText(getApplicationContext(), "竖屏", 0).show();Log.e("test", "竖屏");} else {// 切换成横屏LayoutParams params1 = new RelativeLayout.LayoutParams(screenHeight, screenWidth);videoView.setLayoutParams(params1);Toast.makeText(getApplicationContext(), "横屏", 0).show();Log.e("test", "横屏");}}@Overridepublic void onClick(View arg0) {switch (arg0.getId()) {case R.id.iv_stretch:instance.toggleScreen();break;}}
}

调用了activity.setRequestedOrientation()以后,会触发activity.onConfigurationChanged();可以在这里面重新设置播放界面的大小。

参考:http://download.csdn.net/download/liubo080852/8446445

2.还有一种更简单的方式OrientationEventListener:

public class ScreenOrientationUtil {private int mOrientation;private OrientationEventListener mOrEventListener;private int mOrientation1;private OrientationEventListener mOrEventListener1;private Activity mActivity;private static ScreenOrientationUtil instance = new ScreenOrientationUtil();public static ScreenOrientationUtil getInstance(){return instance;} public void start(Activity activity){this.mActivity = activity;if(mOrEventListener == null){initListener();}mOrEventListener.enable();}public void stop(){if(mOrEventListener != null){mOrEventListener.disable();}if(mOrEventListener1 != null){mOrEventListener1.disable();}}private void initListener(){mOrEventListener = new OrientationEventListener(mActivity) {@Overridepublic void onOrientationChanged(int rotation) {Log.e("test", ""+rotation);if (rotation == OrientationEventListener.ORIENTATION_UNKNOWN) {return;}int orientation = convert2Orientation(rotation);// 方向没有变化,跳过if (orientation == mOrientation) {return;}mOrientation = orientation;mActivity.setRequestedOrientation(mOrientation);}};mOrEventListener1 = new OrientationEventListener(mActivity) {@Overridepublic void onOrientationChanged(int rotation) {if (rotation == OrientationEventListener.ORIENTATION_UNKNOWN) {return;}int orientation = convert2Orientation(rotation);// 方向没有变化,跳过if (orientation == mOrientation1) {return;}mOrientation1 = orientation;if(mOrientation1 == mOrientation){mOrEventListener1.disable();mOrEventListener.enable();}}};}public boolean isPortrait(){if(mOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT || mOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT){return true;}return false;}public int getOrientation(){return mOrientation;}public void toggleScreen(){mOrEventListener.disable();mOrEventListener1.enable();int orientation = 0 ;if(mOrientation ==  ActivityInfo.SCREEN_ORIENTATION_PORTRAIT){orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;}else if(mOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;}else if(mOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE){orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;}else if(mOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT){orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;}mOrientation = orientation;mActivity.setRequestedOrientation(mOrientation);}private int convert2Orientation(int rotation){int orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;if (((rotation >= 0) && (rotation <= 45)) || (rotation > 315)) {orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;} else if ((rotation > 45) && (rotation <= 135)) {orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;} else if ((rotation > 135) && (rotation <= 225)) {orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;} else if ((rotation > 225) && (rotation <= 315)) {orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;} else {orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;}return orientation;}
}

貌似也可以啊!

代码在这里:http://download.csdn.net/detail/goldenfish1919/8999635

Android-加速传感器或者OrientationEventListener做横竖屏切换相关推荐

  1. android 视频播放器 加载字幕,Android 实现视频字幕Subtitle和横竖屏切换示例

    系统自带的VideoView有些视频格式不支持,那么我们可以用第三方实现的VideoView替代系统的来播放视频,比较流行的有ijkplayer.vitamio. 最近有个需求就是需要给视频添加字幕, ...

  2. Android 实现视频字幕Subtitle和横竖屏切换

    转载请标明地址:http://blog.csdn.net/gaolei1201/article/details/62041478 系统自带的VideoView有些视频格式不支持,那么我们可以用第三方实 ...

  3. android dialog横屏,解决dialog在横竖屏切换时消失

    以AlertDialog为例 一.将AlertDialog视图封装在dialogfragment(fragmentdeAlertDialog子类)实例中 package com.example.t; ...

  4. WebView网页视频统一全屏播放及横竖屏切换

    WebView 支持 Html5 video 进行全屏播放及横竖屏自动切换 1.检查AndroidManifest.xml清单文件,WebView控件所在的Activity配置信息;检查Activit ...

  5. Android横竖屏切换小结

    (老样子,图片啥的详细文档,可以下载后观看 http://files.cnblogs.com/franksunny/635350788930000000.pdf) Android手机或平板都会存在横竖 ...

  6. Android横竖屏切换相关知识点

    转载自:http://www.cnblogs.com/franksunny/p/3714442.html (老样子,图片啥的详细文档,可以下载后观看 http://files.cnblogs.com/ ...

  7. Android横竖屏切换小结(重建、非重建Activity)

    来自:http://www.cnblogs.com/franksunny/p/3714442.html (老样子,图片啥的详细文档,可以下载后观看 http://files.cnblogs.com/f ...

  8. Android 横竖屏切换小结

    (自己体会:每次横竖屏自动切时都会run Activity的onCreate,即相当后重新进入Activity初始化一样:) 转自:http://www.cnblogs.com/franksunny/ ...

  9. Android横竖屏切换

    尊重原创,本文转载自 http://www.cnblogs.com/franksunny/p/3714442.html Android横竖屏切换小结 (老样子,图片啥的详细文档,可以下载后观看 htt ...

最新文章

  1. hdu 5366 简单递推
  2. Docker是世界上最牛逼的CaaS!
  3. 多倍体单体型组装算法研究
  4. Toby Walsh教授:四个指数趋势解释人工智能威胁论!
  5. Java线程之线程池
  6. 详解 Weex JS Framework 的编译过程
  7. 《思科UCS服务器统一计算》一导读
  8. Smarty2至Smarty3升级指南
  9. captcha must be filled out_直播行业这些英文单词,不知道你就out了
  10. kubernetes Containerd shim docker关系
  11. tika获取压缩文件内容
  12. Numpy学习---Task03---数组的操作
  13. 超星尔雅python_超星尔雅Python金融数据分析答案公众号
  14. em算法 实例 正态分布_4-EM算法原理及利用EM求解GMM参数过程
  15. 随机地图生成工具 fastMapper
  16. 一、Fiddler抓包工具 — Fiddler介绍与安装
  17. 数据科学、机器学习和数据挖掘的差异
  18. malloc失败的一个原因
  19. YOLOv5训练时出现Corrupt JPEG data: 2 extraneous bytes before marker 0xd9
  20. 目前IT行业最流行的九大前端框架

热门文章

  1. Android QQ登录集成
  2. android adb点击坐标,Android adb shell 获得点击屏幕的位置坐标
  3. DiskGenius 数据恢复工具
  4. C语言用链表实现管理系统
  5. k8s 集群部署(dashboard+metrics-server)
  6. 如何更好的进行技术面试
  7. Svn中可能出现的问题解决办法
  8. js中的定时器和计时器使用
  9. JavaScript中classList属性和className的区别
  10. 安装npm和cnpm