Thursday, September 24, 2009

Orientation change trick

     Today I was in need of stopping my application from resetting after the orientation change. What happens when the orientation change?
     Well, first of all the orientation change is managed by the default activity handler. And the default handling for this event is to restart an activity.
     What you need to do to stop the activity to be default handled is:

        1. Go to the manifest XML file and in the activity tag add the following attribute:

        android:configChanges="orientation"

        Now if you'll run the application an rotate the screen you will get the "java.lang.OutOfMemoryError: bitmap size exceeds VM budget" exception because the system runs out of memory since it still creates a new activity but the previous is not destroyed. So the solution is not solved yet.
 
       2. For the custom orientation change handling to actually take place you need also to override onConfigurationChanged method.

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



     Right now the problem is solved and you can change the orientation as many times as you like without the activity to get restarted.
     If you still get the "java.lang.OutOfMemoryError: bitmap size exceeds VM budget" exception it means that you have a little memory leak. You can find some advices on how to solve memory leaks problems here.
     If you get to try this solution you may want to take a look on the documentation and find out which other  config changes  you may manage manually.

No comments:

Post a Comment