Thursday, January 29, 2015
Android beginner tutorial Part 56 Activity stacks and tasks
In Android all Activity objects are saved in a stack. Whenever an Activity launches another Activity, the new one is moved to the stack and becomes the active Activity. The previous one also remains in the stack, but it is moved lower. Activity objects in a stack are never repositioned, they can only be added or removed.
When the user presses the Back button on their device, the current Activity is pushed out of the stack and is replaced with the previous one, which becomes visible again.
If there are multiple Activities of the same class in a stack, they are treated as separate instances.
A stack with Activities in it is called a task, which can be put in the foreground, when one of its Activities is currently active, or in the background, where its completely out of user focus.
If the user doesnt interact with a task for a long period of time, the system clears all of that tasks Activities, except for the main one. To save the state of an Activity before it is destroyed, which is done after the onDestroy() method is called, you can use the onSaveInstanceState() method. Android calls it before creating an Activity, before calling onPause().
The system sends a Bundle object this way, which can be used to store some data to later be able to recreate the same Activity state. When the Activity is once again called, the system kindly sends the Bundle with all the parameters youve written as a parameter of the onCreate() method, as well as the onRestoreInstanceState() method, which is called after onStart(), so that one of them (or both) could return the Activity to what it looked like before.
The onSaveInstanceState() and onRestoreInstanceState() methods are not a part of the lifecycle of an Activity. They wont always be called by the system. For example, the onSaveInstanceState() method is called when the Activity become vulnerable to being destroyed by the system, but it isnt called if the user willingly closes it. Thats good, because it is an intuitive and expected behaviour.
Because onSaveInstanceState() is not always called, if youre saving data you should do that when the application gets paused - in the onPause() function.
That way it will be possible to later restart the destroyed Activity (if the system decides to destroy it) with the saved previous state.
That is all for today.
Thanks for reading!
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.