View on GitHub

Bearded-android-docs

ActivityLifeCycle

Download this project as a .zip file Download this project as a tar.gz file

Created Wednesday 28 August 2013

Activity States

                                    +----------+
                       onResume()-->| Resumed  |--->onPause()--o
                          ^         | (visible)|               |
                          |         +-----+----+               |
                     +----+-----+         ^           +--------+----------+
         onStart()-->| Started  |       onResume()<---|    Paused         |
              ^      | (visible)|                     |(partially visible)|
         +----+----+ +-----+----+                    +--------+----------+
   +---->| Created |       ^                                  |
   |     +---------+       |                               onStop()
onCreate()                 |                                  |
                           |                           +------+--+
                         onRestart()<------------------| Stopped |----->onDestroy()
                                                       +---------+

An activity can exist in essentially three states:

If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling its finish() method), or simply killing its process. When the activity is opened again (after being finished or killed), it must be created all over.

Note: In extreme cases, when the system is super low on memory, onDestroy() may never be called! However, onStop() is always called.

Pausing an Activity

Note: onPause() is designed to be lightweight! Do heavyweight housekeeping like database access in onStop()

Stopping an Activity

Because the system retains your Activity instance in system memory when it is stopped, it's possible that you don't need to implement the onStop() and onRestart() (or even onStart() methods at all. For most activities that are relatively simple, the activity will stop and restart just fine and you might only need to use onPause() to pause ongoing actions and disconnect from system resources.

Recreating an Activity

When data to save is simple:

Disadvantage is that a Bundle stores objects with Parcelable (so it can be expensive). You may also need to reinstantiate expensive objects such as network connections. This can make rotating the phone seem sluggish. An alternative:

Note: watch out for memory leaks! Don't store the Activity or anything associated with its Context.


No backlinks to this page.
comments powered by Disqus