[Android development] Activity life cycle

4 states

  • Running status: The current Activity is in the foreground, visible to the user, and can be focused.
  • Paused state: other activities are in the foreground, the activity is still visible, but can not get the focus.
  • Stop state: The Activity is invisible and loses focus.
  • Destroyed state: The activity ends, or the process in which the activity is located is ended.

State transition

  1. Load Activity
  2. onCreate(Bundle savedStatus): Called back when creating Activity. This method can only be used once.
  3. onStart(): Called back when the Activity is started.
  4. onResume (): Activity enters the foreground and can start interaction.
  5. Operating status
  6. onPause(): Call back this method after other activities are transferred to the foreground.
  7. Suspended state
    1. Back to onResume(), the Activity will return to the foreground
  8. onStop (): The Activity will become completely invisible.
  9. Stopped state
    1. onRestart(): The user starts the Activity again, makes it enter the foreground, and returns to onStart()
    2. A higher priority application needs memory, the application process is terminated, the user starts the Activity again, and returns to onCreate()
  10. onDestroy () : The Activity is destroyed alive by the end of the system.
  11. Destroyed state

Common state transitions

The life cycle of a single Activity

  1. Start normally onCreate -> onStart -> onResume
    Exit normally onPause -> onStop -> onDestory
    Start onCreate -> onStart -> onResume again
  2. Activity already in the foreground, click the home button to leave the current Activity, onPause -> onStop
    to return to the Activity: onRestart -> onStart -> onResume
  3. Activity cannot operate onPause -> onStop (such as: stop screen, open other Activity), the application is forcibly killed
    and then return to Activity, onCreate -> onStart -> onResume

When multiple activities are switched

When another Activity is started, the current Activity: onPause -> onStop
When the return button is clicked to make another Activity exit, the current Activity: onRestart -> onStart -> onResume

Dialog box

  • Normal dialog box does not affect the life cycle
    //打开对话框
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("提示") //对话框标题
            .setMessage("Message") //对话框内容
            .setPositiveButton("OK", null) //参数1:返回文字;参数2:返回后做的事情
            .show(); //展示
  • If there is an Activity disguised as a dialog mode, then when it starts, the previous Activity: onPause
    "dialog" disappears, the callback onResume returns to the foreground again

Set Acitvity disguised as a dialog

<activity android:name=".DialogActivity" android:theme="@style/Theme.AppCompat.Dialog">

Start Activity

   Intent it = new Intent(this, DialogActivity.class);
   startActivity(it);

Guess you like

Origin blog.csdn.net/weixin_42020386/article/details/112802242