Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register a listener for orientation change?

My android app will run at background and I need to be notify immediately when orientation change. eg. When user rotate the phone from portrait to landscape (or landscape to portrait), the system should be tell my app that the orientation has changed.

Thanks.

like image 862
Nguyen Minh Binh Avatar asked Apr 28 '12 08:04

Nguyen Minh Binh


2 Answers

This method is called when screen rotated

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
        //Do stuff here
}
like image 178
Rafiq Avatar answered Oct 20 '22 22:10

Rafiq


You do not have to explicitly set the Orientation listener.

onConfigurationChanged will be called by the system.

@Override
public void onConfigurationChanged(Configuration myConfig) {
    super.onConfigurationChanged(myConfig);
    int orient = getResources().getConfiguration().orientation; 
    switch(orient) {
                case Configuration.ORIENTATION_LANDSCAPE:
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    break;
                case Configuration.ORIENTATION_PORTRAIT:
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    break;
                default:
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                }
}
like image 34
Arif Nadeem Avatar answered Oct 20 '22 23:10

Arif Nadeem