本文概述

Android Activity生命周期由android.app.Activity类的7种方法控制。 android Activity是ContextThemeWrapper类的子类。
活动是android中的单个屏幕。它就像Java的窗口或框架。
在活动的帮助下,你可以将所有UI组件或小部件放在一个屏幕中。
Activity的7个生命周期方法描述了Activity在不同状态下的行为。
Android Activity生命周期方法
让我们看看android活动的7种生命周期方法。
方法 | 描述 |
---|---|
onCreate | 在首次创建活动时调用。 |
onStart | 当活动对用户可见时调用。 |
onResume | 当活动开始与用户互动时调用。 |
onPause | 在用户看不到活动时调用。 |
onStop | 当活动不再对用户可见时调用。 |
onRestart | 活动停止后, 开始之前调用。 |
onDestroy | 在活动销毁之前调用。 |

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.srcmini02.com.activitylifecycle.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Android活动生命周期示例
它提供了有关活动生命周期方法调用的详细信息。在此示例中,我们在logcat上显示内容。
package example.srcmini02.com.activitylifecycle;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle", "onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle", "onStart invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d("lifecycle", "onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle", "onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("lifecycle", "onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle", "onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("lifecycle", "onDestroy invoked");
}
}
输出:
你不会在仿真器或设备上看到任何输出。你需要打开logcat。

现在在logcat上看到:调用了onCreate,onStart和onResume方法。

现在点击HOME按钮。你将看到onPause方法被调用。

一段时间后,你将看到onStop方法被调用。

现在在模拟器上查看。在家里。现在,单击中心按钮以再次启动该应用程序。

现在,单击lifecycleactivity图标。

现在在logcat上看到:调用了onRestart,onStart和onResume方法。

如果看到模拟器,则将再次启动应用程序。

现在单击后退按钮。现在你将看到onPause方法被调用。

一段时间后,你将看到onStop和onDestroy方法被调用。
