Get phone orientation but fix screen orientation to portrait

前端 未结 7 1247
忘了有多久
忘了有多久 2020-12-01 09:09

I want to get the phone orientation but keep the screen orientation to portrait. So no matter the user turns the phone to landscape or portrait, the view stays the same, but

7条回答
  •  长情又很酷
    2020-12-01 09:40

    I needed a solution that would give me the orientation only on-demand. This one worked for me:

    public class SensorOrientationChecker {
    
    public final String TAG = getClass().getSimpleName();
    
    int mOrientation = 0;
    private SensorEventListener mSensorEventListener;
    private SensorManager mSensorManager;
    
    private static SensorOrientationChecker mInstance;
    
    public static SensorOrientationChecker getInstance() {
        if (mInstance == null)
            mInstance = new SensorOrientationChecker();
    
        return mInstance;
    }
    
    private SensorOrientationChecker() {
        mSensorEventListener = new Listener();
        Context applicationContext = GlobalData.getInstance().getContext();
        mSensorManager = (SensorManager) applicationContext.getSystemService(Context.SENSOR_SERVICE);
    
    }
    
    /**
     * Call on activity onResume()
     */
    public void onResume() {
        mSensorManager.registerListener(mSensorEventListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
    }
    
    /**
     * Call on activity onPause()
     */
    public void onPause() {
        mSensorManager.unregisterListener(mSensorEventListener);
    }
    
    private class Listener implements SensorEventListener {
    
        @Override
        public void onSensorChanged(SensorEvent event) {
            float x = event.values[0];
            float y = event.values[1];
    
            if (x<5 && x>-5 && y > 5)
                mOrientation = 0;
            else if (x<-5 && y<5 && y>-5)
                mOrientation = 90;
            else if (x<5 && x>-5 && y<-5)
                mOrientation = 180;
            else if (x>5 && y<5 && y>-5)
                mOrientation = 270;
    
            //Log.e(TAG,"mOrientation="+mOrientation+"   ["+event.values[0]+","+event.values[1]+","+event.values[2]+"]");
                                                                           }
    
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
    
        }
    
    }
    
    public int getOrientation(){
        return mOrientation;
        }
    }
    

提交回复
热议问题