Книга: Beginning Android

The Grace of State

The Grace of State

Mostly, the aforementioned methods are for dealing with things at the application-general level (e.g., wiring together the last pieces of your UI in onCreate(), closing down background threads in onPause()).

However, a large part of the goal of Android is to have a patina of seamlessness. Activities may come and go as dictated by memory requirements, but users are, ideally, unaware that this is going on. If, for example, they were using a calculator, and come back to that calculator after an absence, they should see whatever number(s) they were working on originally — unless they themselves took some action to close down the calculator.

To make all this work, activities need to be able to save their application-instance state, and to do so quickly and cheaply. Since activities could get killed off at any time, activities may need to save their state more frequently than one might expect. Then, when the activity restarts, the activity should get its former state back, so it can restore the activity to the way it appeared previously.

Saving instance state is handled by onSaveInstanceState(). This supplies a Bundle into which activities can pour whatever data they need (e.g., the number showing on the calculator’s display). This method implementation needs to be speedy, so do not try to be too fancy — just put your data in the Bundle and exit the method.

That instance state is provided to you again in:

• onCreate()

• onRestoreInstanceState()

It is your choice when you wish to re-apply the state data to your activity — either callback is a reasonable option.

Оглавление книги

Оглавление статьи/книги

Генерация: 1.119. Запросов К БД/Cache: 3 / 1
поделиться
Вверх Вниз