开发者

Lifecycle of a simple Android application

I've got a simple application with 3 activities:

  • the first contains a search box which calls a web service and show the results (restaurants) below in a listview
  • when a restaurant is clicked another activity is started showing the description of the restaurant and a button "show map"
  • when the button "show map" is clicked, guess what, the map is shown in a third activity.

All the data is loaded in the first activity by a web service (restaurant descriptions and coordinates), and data required by each activity is passed in a bundle using intent.putExtra.

Now everything seems to run smoothly when clicking on the back button (eg. clicking on the back button from the map resumes the restaurant description activity with all data set properly), while I haven't done anything about the lifecycle yet.

Why? Are all variables saved automatically?开发者_运维知识库 Should I use onSaveInstanceState() and onRestoreInstanceState() anyway?

Thanks

Jul


When new activity B starts on top of another activity A, activity A will not be destroyed by default, it becomes stopped and after that you just resume it. If system needs resources, it can destroy stopped activity. There is a nice graph here that really explains lifecycles of components.


When your activity is stopped, the Activity object is kept resident in memory and is recalled when the activity resumes. You don’t need to re-initialize components that were created during any of the callback methods leading up to the Resumed state. The system also keeps track of the current state for each View in the layout, so if the user entered text into an EditText widget, that content is retained so you don't need to save and restore it.

Even if the system destroys your activity while it's stopped, it still retains the state of the View objects (such as text in an EditText) in a Bundle (a blob of key-value pairs) and restores them if the user navigates back to the same instance of the activity).

http://developer.android.com/training/basics/activity-lifecycle/stopping.html

By default, the system uses the Bundle instance state to save information about each View object in your activity layout (such as the text value entered into an EditText object). So, if your activity instance is destroyed and recreated, the state of the layout is restored to its previous state with no code required by you. However, your activity might have more state information that you'd like to restore, such as member variables that track the user's progress in the activity.

Note: In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.

To save additional data about the activity state, you must override the onSaveInstanceState() callback method.

http://developer.android.com/training/basics/activity-lifecycle/recreating.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜