Phone orientation detection with sensor events

I have an Activity that requires its orientation to be locked using

setRequestedOrientation(screenOrientation); 

But I want to receive orientation updates so that I can adjust the user interface (imagine an application for the HTC camera when only the icon buttons change orientation). So I found this class . It passes orientation values ​​from 0 to 360. Ho, I filter these values, i.e. The ideal interval is [a, b] , and if a<x<b , then is the orientation a landscape or a portrait? Calculate the average? Any clues?

+7
source share
1 answer

It looks like you need a code that only responds when the device’s orientation changes to one of four normal orientations, and not at every angle. This will allow you to filter the orientation only at values ​​of 0, 90, 180 and 270 degrees:

 OrientationEventListener myOrientationEventListener; int iOrientation; myOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) { @Override public void onOrientationChanged(int iAngle) { // 0 15 30 45 60 75, 90 105, 120, 135, 150, 165, 180, 195, 210, 225, 240, 255, 270, 285, 300, 315, 330, 345 final int iLookup[] = {0, 0, 0,90,90, 90,90, 90, 90, 180, 180, 180, 180, 180, 180, 270, 270, 270, 270, 270, 270, 0, 0, 0}; // 15-degree increments if (iAngle != ORIENTATION_UNKNOWN) { int iNewOrientation = iLookup[iAngle / 15]; if (iOrientation != iNewOrientation) { iOrientation = iNewOrientation; // take action on new orientation here } } } }; // To display if orientation detection will work and enable it if (myOrientationEventListener.canDetectOrientation()) { Toast.makeText(this, "Can DetectOrientation", Toast.LENGTH_LONG).show(); myOrientationEventListener.enable(); } else { Toast.makeText(this, "Can't DetectOrientation", Toast.LENGTH_LONG).show(); } 
+7
source

All Articles