本文實例講述了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程序設計有所幫助。
新聞熱點
疑難解答