onDestroy() is mostly for cleanly releasing resources you obtained in onCreate() (if any).

onStart(), onRestart(), and onStop()

An activity can come to the foreground either because it is first being launched, or because it is being brought back to the foreground after having been hidden (e.g., by another activity or by an incoming phone call).

The onStart() method is called in either of those cases. The onRestart() method is called in the case where the activity had been stopped and is now restarting.

Conversely, onStop() is called when the activity is about to be stopped.

onPause() and onResume()

The onResume() method is called just before your activity comes to the foreground, either after being initially launched, being restarted from a stopped state, or after a pop-up dialog (e.g., incoming call) is cleared. This is a great place to refresh the UI based on things that may have occurred since the user was last looking at your activity. For example, if you are polling a service for changes to some information (e.g., new entries for a feed), onResume() is a fine time to both refresh the current view and, if applicable, kick off a background thread to update the view (e.g., via a Handler).

Conversely, anything that steals your user away from your activity — mostly, the activation of another activity — will result in your onPause() being called. Here, you should undo anything you did in onResume(), such as stopping background threads, releasing any exclusive-access resources you may have acquired (e.g., camera), and the like.

Once onPause() is called, Android reserves the right to kill off your activity’s process at any point. Hence, you should not be relying upon receiving any further events.

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.

PART 3

Data Stores, Network Services, and APIs 

CHAPTER 17

Using Preferences

Android has many different ways for you to store data for long-term use by your activity. The simplest to use is the preferences system.

Android allows activities and applications to keep preferences, in the form of key/value pairs (akin to a Map), that will hang around between invocations of an activity. As the name suggests, the primary purpose is for you to store user-specified configuration details, such as the last feed the user looked at in your feed reader, or what sort order to use by default on a list, or whatever. Of course, you can store in the preferences whatever you like, so long as it is keyed by a String and has a primitive value (boolean, String, etc.).

Preferences can either be for a single activity or shared among all activities in an application. Eventually preferences might be shareable across applications, but that is not supported as of the time of this writing.

Getting What You Want

To get access to the preferences, you have three APIs to choose from:

• getPreferences() from within your Activity, to access activity-specific preferences

• getSharedPreferences() from within your Activity (or other application Context), to access application-level preferences

• getDefaultSharedPreferences(), on PreferencesManager, to get the shared preferences that work in concert with Android’s overall preference framework

The first two take a security-mode parameter — for now, pass in 0. The getSharedPreferences() method also takes a name of a set of preferences — getPreferences() effectively calls getSharedPreferences() with the activity’s class name as the preference set name. The getDefaultSharedPreferences() method takes the Context for the preferences (e.g., your Activity).

All of those methods return an instance of SharedPreferences, which offers a series of getters to access named preferences, returning a suitably typed result (e.g., getBoolean() to

Вы читаете Beginning Android
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату