本文实例讲述了Android编程基于重力传感器实现横竖屏放向切换功能。分享给大家供大家参考,具体如下: 最近项目中用到了vr视频播放,因为自己实现,同时要实现横竖屏自动切换屏幕
本文实例讲述了Android编程基于重力传感器实现横竖屏放向切换功能。分享给大家供大家参考,具体如下:
最近项目中用到了vr视频播放,因为自己实现,同时要实现横竖屏自动切换屏幕,核心代码如下:
package com.d1ev.touch.App.helper; import android.app.Activity; import android.content.pm.ActivityInfo; import android.util.Log; import android.view.OrientationEventListener; import java.lang.ref.WeakReference; /** * Created by Administrator on 2016/12/3 0003. * 监听重力系统传感器的变化,为Vr视频播放器而定制 */ public class MySensorHelper { private static final String TAG = MySensorHelper.class.getSimpleName(); private OrientationEventListener mLandOrientationListener; private OrientationEventListener mPortOrientationListener; private WeakReference<Activity> mActivityWeakRef; private boolean isPortLock = false; private boolean isLandLock=false; public MySensorHelper(final Activity activity) { this.mActivityWeakRef = new WeakReference(activity); this.mLandOrientationListener = new OrientationEventListener(activity, 3) { public void onOrientationChanged(int orientation) { Log.d(MySensorHelper.TAG, "mLandOrientationListener"); if(orientation < 100 && orientation > 80 || orientation < 280 && orientation > 260) { Log.e(MySensorHelper.TAG, "转到了横屏"); if(!MySensorHelper.this.isLandLock) { Activity mActivity = (Activity)MySensorHelper.this.mActivityWeakRef.get(); if(mActivity != null) { Log.e(MySensorHelper.TAG, "转到了横屏##################"); mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); isLandLock=true; isPortLock=false; } } } } }; this.mPortOrientationListener = new OrientationEventListener(activity, 3) { public void onOrientationChanged(int orientation) { Log.w(MySensorHelper.TAG, "mPortOrientationListener"); if(orientation < 10 || orientation > 350 || orientation < 190 && orientation > 170) { Log.e(MySensorHelper.TAG, "转到了竖屏"); if(!MySensorHelper.this.isPortLock) { Activity mActivity = (Activity)MySensorHelper.this.mActivityWeakRef.get(); if(mActivity != null) { Log.e(MySensorHelper.TAG, "转到了竖屏!!!!!!!!!!!!!!!!!!!!!!"); mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); isPortLock=true; isLandLock=false; } } } } }; //this.disable(); } //禁用切换屏幕的开关 public void disable() { Log.e(TAG, "disable"); this.mPortOrientationListener.disable(); this.mLandOrientationListener.disable(); } //开启横竖屏切换的开关 public void enable(){ this.mPortOrientationListener.enable(); this.mLandOrientationListener.enable(); } //设置竖屏是否上锁,true锁定屏幕,fanle解锁 public void setPortLock(boolean lockFlag) { this.isPortLock = lockFlag; } //设置横屏是否锁定,true锁定,false解锁 public void setLandLock(boolean isLandLock){ this.isLandLock=isLandLock; } }
使用时将当前activity对象传过来即可,但要在activity的ondestory()
方法里面或者back键的监听里面禁用屏幕监听,否则会造成activity不能被回收而导致内存泄漏
helper.disable();
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》、《Android视图View技巧总结》、《Android编程之activity操作技巧总结》、《Android文件操作技巧汇总》、《Android资源操作技巧汇总》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。