How to receive onConfigurationChanged events (Android SDK)

1.1k views Asked by At

The goal is to fix the screen layout as "landscape" or "portrait" and continue to receive rotation events. I know about onConfigurationChanged(Configuration newConfig) in Activity but it does not work with fixed layouts. How to deal with this? To explain more clearly I want to implement a behaviour like in Android Camera application - rotate only button images but not reload activity and not change the layout.

EDIT#1: I mean this method does not work after calling setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)

EDIT#2: Yes, onConfigurationChanged was not what I need. Instead SensorEventListener interface should be implemented and check for onSensorChanged events.
Complete solution, taken from Get phone orientation but fix screen orientation to portrait:

public class MainActivity extends Activity implements SensorEventListener {
int orientation = -1;
@Override
public void onSensorChanged(SensorEvent event) {
    if (event.values[1] < 6.5 && event.values[1] > -6.5) {
        if (orientation != 1) {
        Toast toast = Toast.makeText(getApplicationContext(), "LANDSCAPE", Toast.LENGTH_SHORT); 
        toast.show(); 
    }
    orientation = 1;
    } else {
        if (orientation != 0) {
        Toast toast = Toast.makeText(getApplicationContext(), "PORTRAIT", Toast.LENGTH_SHORT); 
        toast.show(); 
        }
    orientation = 0;
    }
}

And this works excellent with this AndroidManifest setting for your activity:

android:screenOrientation="landscape"
1

There are 1 answers

1
NehaK On

You have to declare it in manifest file of your project-

    <activity
        android:name="your_activity_name"
        android:configChanges="orientation" >
    </activity>

And override method

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

in your activity class.