Android Tutorial: Activity Lifecycle

 ·  · 

Android Activity lifecycle.

 

1 Lifecycle overview

An overview of Android Activity entire lifetime by official reference.

android-activity-lifecycle-official

Android Activity life can be divided into six states illustrated by guide at Android Developers website.

android-activity-lifecycle-states

  • Created
  • Started
  • Resumed
  • Paused
  • Stopped
  • Destroyed

 

2 Lifecycle methods

android-activity-lifecycle-methods

onCreate():

onCreate() will be called when the activity is first created. This is the right place to setup views, load initial data.

onStart():

Invoked when the activity is becoming visible to the user. Activity cannot get focus or interact with user at this point.

onResume():

Invoked when the activity will start interacting with the user. The activity comes to the foreground after this method called.

onPause():

This method is the counterpart of onResume(). It will be called when the activity is going to lost focus but is still visible, totally or partially. The activity is no longer foreground activity after this method called.

onStop():

Invoked when the activity is no longer visible to the user but is still alive in system memory. The activity is becoming a background activity.

onRestart():

Invoked after the activity has been stopped, but prior to it being started again. Always followed by onStart().

onDestroy():

Called before the activity is destroyed.

3 Typical interactive scenarios

Launch an activity:

onCreate() => onStart() => onResume()

Press the Back key of the phone to exit current activity:

onPaused() => onStop() => onDestory()

Press the Home key of the phone:

onPaused() => onStop()

After pressing the Home key of the phone, reopen the app from Android recent task list or by clicking app launcher icon:

onRestart() => onStart() => onResume()

Start Activity B from current Activity A:

A:onPause() => B:onCreate() => B:onStart() => B:onResume => A:onStop()

Change screen orientation:

onPaused() => onStop() => onDestory() => onCreate() => onStart() => onResume()

User is interacting with current Activity, then answer an incoming call, at last hang up after talking:

[click answer button] => onPause() => [talking] => [hang up] => onResume() 

Lock screen:

onPaused() => onStop()

Unlock screen:

onRestart() => onStart() => onResume()