Saturday, April 9, 2011

Opting out of onCreate()

Today in my Android development I had a need for one of my activities to perform a task only when it is first created. Activities in Android follow a defined life cycle which I pasted below from the site under the documentation for the Activity class. 

The difficulty is that there isn't always a life cycle method that is only called only when an activity is first created. During configuration changes Android will destroy your activity and create it again. Most of the time this is necessary because you may have different layouts for different orientations or actions and so the only safe thing to do is to destroy and create your activity again. There is a way to circumvent this and it is detailed in a section of the Activity class documentation but I think it is worth pointing out here.

You must do two things:

  1. Edit you manifest file under your activity's node and give it: android:configChanges="orientation|keyboardHidden". This will tell Android that you are going to handle these events manually.
  2. Override the method onConfigurationChanged(Configuration newConfig) in your activity. 
Now that you have done that onCreate() will only be called once when your activity first loads. Just be aware of the side effect. Any special layout that you have for your Activity will not be loaded when your orientation changes.