您好,登錄后才能下訂單哦!
小編給大家分享一下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中如何使用重力傳感器實現橫豎屏放向切換功能”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。