25
CHAPTER 3: Activities
necessary to preserve the state of an app. For example, if an activity
will not be destroyed
but just suspended, the state is going to be kept anyway, and
onSaveInstanceState()
and
onRestoreInstanceState()
will not be invoked.
Android helps us here: the default implementations of
onSaveInstanceState()
and
onRestoreInstanceState()
already save and restore UI elements that have an ID. So, if
that is all you need, you don’t have to do anything. Of course,
your activity might be more
complex and may contain other fields you need to preserve. In this case, you can override
both
onSaveInstanceState()
and
onRestoreInstanceState()
. Just make sure you call the
superclass’s methods; otherwise, you must take care of all UI elements yourself.
override
fun onSaveInstanceState(outState:Bundle?) {
super.onSaveInstanceState(outState)
// add your own data to the Bundle here...
// you can use one of the put* methods here
// or write
your own Parcelable types
}
override
fun onRestoreInstanceState(savedInstanceState: Bundle?) {
super.onRestoreInstanceState(savedInstanceState)
// restore your own data from the Bundle here...
// use one of the get* methods here
}
Note that the saved state goes to the
onCreate()
callback as well, so it is up to you whether
you want to use the
onRestoreInstanceState()
or
onCreate()
method for restoring the state.
Under these circumstances, the standard mechanism for saving
and restoring state might
not suit your needs. For example, it can’t preserve data when you stop your app. In this
case, the
onSaveInstanceState()
method is not getting called. If you need to preserve data
in such cases, you can use
onDestroy()
to save your app’s data
in a database and read the
database during the
onCreate()
callback. See Chapter
8
for more information.
27
© Peter Späth 2018
P. Späth,
Pro Android with Kotlin
,
https://doi.org/10.1007/978-1-4842-3820-2_4
Chapter
4
Services
Services are components running without a user interface and with a conceptual affinity
toward long-running processes. They are separate from notifications in the
status bar
or a
Toast
. Services
can be started by apps, or they can be bound to by apps, or both.
Services come in two flavors: foreground services and background services. While at first
glance it seems to be a contradiction to speak of “foreground” services since so many
people tend to say that “services run in the background,” foreground services do actually
exist. The distinction between foreground and background services
is crucial because their
behaviors are different.
Caution
Do not misinterpret services as constructs for running anything that needs to be
calculated in the background, in other words, not disturbing GUI activities. If you need a process
that does not interfere with the GUI but is otherwise not eligible to run while your app is inactive
and also not subject to being
used from outside your app, consider using a thread instead. See
Chapter
10
for more information.