Andrew Quebe
Andrew Quebe

Reputation: 2293

Android App Development: Handling Screen Orientation Changes

I have run into a problem with handling screen orientation changes (For example: portrait to landscape). I'm developing a flashlight app which has a toggle button that turns the LED light on or off on the person's phone. I set up my onPause() method to kill the app like so:

    @Override
    protected void onPause() {
         super.onPause();
         finish();
    }

This is because if I was to open the app and then go something else (like open youtube) and then come back and press the button again it crashes. But because of this "finish();" thing I can't handle screen orientation changes because apparently when it switches orientation it calls the onPause() method which finishes!

SO my question is...how do I do both? I want to be able to fix the crash problem but also not have it crash when the screen orientation changes. I'm not asking for code (although it would be helpful) just some insight from a new set of eyes.

I thought about using an "if" statement...would this work?

Thanks in advance, Andrew

Upvotes: 1

Views: 3002

Answers (1)

Euporie
Euporie

Reputation: 1986

When the screen orientation changes, the activity will do onPause(), onStop() and onCreate() again. If you don't want your activity do onPause when the orientation changes, try this:

  1. In your manifest.xml, add android:configChanges="orientation|keyboardHidden" for your activity like:

    <activity android:name=".yourname"
              android:configChanges="orientation|keyboardHidden">
    </activity>
    
  2. In your activity, override this method:

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

But my advice is not to use finish() in onPause(), the system can handle the lifecycle just fine. If you want to finish your activity when the home or back button pressed, try to override onBackPress() and onUserLeaveHint(), these two method can catch back and home button pressed, and add finish() in these two method.

Hope it helps.

Upvotes: 3

Related Questions