10. Activity life cycle

10.1. States of an activity

An activity can be in different states depending how it is interacting with the user. These states are described by the following table.

Table 2. Activity state
State Description

Running

Activity is visible and interacts with the user.

Paused

Activity is still visible but partially obscured, instance is running but might be killed by the system.

Stopped

Activity is not visible, instance is running but might be killed by the system.

Killed

Activity has been terminated by the system of by a call to its finish() method.

10.2. The live cycle methods

The Android system defines a life-cycle for activities via predefined life-cycle methods. The most important methods are: .Important Activity lifecycle methods

Method Purpose

onCreate()

Called then the activity is created. Used to initialize the activity, for example create the user interface.

onResume()

Called if the activity get visible again and the user starts interacting with the activity again. Used to initialize fields, register listeners, bind to services, etc.

onPause()

Called once another activity gets into the foreground. Always called before the activity is not visible anymore. Used to release resources or save application data. For example you unregister listeners, intent receivers, unbind from services or remove system service listeners.

onStop()

Called once the activity is no longer visible. Time or CPU intensive shut-down operations, such as writing information to a database should be down in the onStop() method. This method is guaranteed to be called as of API 11.

The life cycle of an activity with its most important methods is displayed in the following diagram.

Activity life cycle

Android has more life cycle methods but not all of these methods are guaranteed to be called. TheonDestroy() method is not guaranteed to be called, hence you typically do not use it.