Detecting device orientation

deimus picture deimus · Jun 28, 2012 · Viewed 8.7k times · Source

I need to detect android device orientation change without playing manually with sensor data, while keeping activity orientation stick to some orientation

onConfigurationChange will not work as will stick my activity to not rotate.

Playing around with sensor data to detect the orientation change I consider that as an invention of wheel, as android already does have embedded implementation of the algorithm to detect device orientation change. And from another side the detection of orientation change is not a simple checks like this.

    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER || event.values.length < 3) {
            return;
        }
        //getResources().getConfiguration().orientation;
        if (event.values[1] < 6.5 && event.values[1] > -6.5) {
            if (orientation!=1) {
                Log.d("Sensor", "Protrait");
            }
            orientation=1;
        } else {
            if (orientation!=0) {
                Log.d("Sensor", "Landscape");
            }
            orientation=0;
        }
   }

It does really require real data processing like filtration from noise and sudden short shakes/rotations.

So any ideas how the device orientation can be detected using legacy services ? (Once again, I'll stick my activity to some orientation so onConfigurationChange will not work)

Answer

rajpara picture rajpara · Jun 28, 2012