April 27, 2011

Single Instance and Single Task

Run any application on an Android device and try various cases. In particular, note the following:
1)  Changing the screen orientation destroys and recreates the activity from scratch.
2)  Pressing the Home button pauses the activity, but does not destroy it.
3)  Pressing the Application icon might start a new instance of the activity, even if the
old one was not destroyed.
4)  Letting the screen sleep pauses the activity and the screen awakening resumes it.
(This is similar to taking an incoming phone call.)


As an application is navigated away from and launched again, it can lead to multiple instances of the activity on the device. Eventually the redundant instance of the activity is killed to free up memory, but in the meantime, it can lead to odd situations.To avoid these, the developer can control this behavior for each activity in the AndroidManifest. To ensure only one instance of the activity runs on the device, specify the following in an activity element that has the MAIN and LAUNCHER intent filters:


This keeps a single instance of each activity in a task at all times. In addition, any child activity is launched as its own task.To constrain even further to only have a single task for all activities of an application, use the following:


This allows the activities to share information easily as the same task.In addition, it might be desirable to retain the task state, regardless of how a user navigates to the activity. For example, if a user leaves the application and relaunches it later, the default behavior often resets the task to its initial state.To ensure the user always returns to the task in its last state, specify the following in the activity element of the root activity of a task:


This is the best way to control the memory utilization for the app as these days its completely multi-tasking!!!