android生命周期




Activity is one of the primary components of an Android application. In this tutorial, we’ll be looking at the android activity lifecycle, and the various functions invoked in the different stages of an Activity’s runtime.

活动是Android应用程序的主要组件之一。 在本教程中,我们将研究android Activity的生命周期,以及在Activity运行时的不同阶段调用的各种函数。

(Android Activity Lifecycle Flow Diagram)

An Activity is a single focused thing that the user can see. Let’s see how the lifecycle of an Activity looks like, which functions are triggered when and why, through a flow diagram.

活动是用户可以看到的唯一关注的事物。 让我们看看活动的生命周期如何,通过流程图何时何地触发了哪些功能。





(Android Activity Lifecycle Stages)

The android activity goes through following lifecycle stages.

android活动将经历以下生命周期阶段。

  • Create
  • Start
  • Pause
  • Resume
  • Stop
  • Restart
  • Destroy

There are specific callback functions for each of these lifecycle stages.

每个生命周期阶段都有特定的回调函数。

(Android Activity Lifecycle Functions)

Let’s look at the lifestyle functions of an activity.

让我们看一下一项活动的生活方式功能。





(1. onCreate())

This is the first stage of an activity lifecycle. This function is called when the activity is initialized.

这是活动生命周期的第一阶段。 活动初始化时将调用此函数。

In our Kotlin Activity class, the following function defines onCreate():

在我们的Kotlin Activity类中,以下函数定义了onCreate()

fun onCreate(savedInstanceState: Bundle?)

We’ll look at what the bundle value contains in a later section.

我们将在后面的部分中查看bundle的值。

(2. onStart())

In this lifecycle stage, the activity is ready to process. This function is called when the activity comes into the foreground but it isn’t interactive yet.

在此生命周期阶段,活动已准备就绪。 当活动进入前台但尚未交互时,将调用此函数。

(3. onResume())

This is where the activity is executing. This function is called when the user is interacting with the activity.

这是活动执行的地方。 当用户与活动进行交互时,将调用此函数。

(4. onPause())

This function is called when the user interaction with the activity isn’t possible.

当用户无法与活动进行交互时,将调用此函数。

Common scenarios: An incoming call comes up. Another application pops up. With the introduction of Android N and the multi-window feature, multiple apps are visible on the screen at one time. Apps that are not in focus would have the onPause() method triggered.

常见情况 :出现来电。 弹出另一个应用程序。 引入Android N和多窗口功能后,一次可在屏幕上看到多个应用程序。 没有重点关注的应用将触发onPause()方法。

(5. onStop())

This function gets triggered when the activity is no longer visible and it has stopped working.

当活动不再可见并且已停止工作时,将触发此功能。

(6. onDestroy())

This function gets triggered when the activity is destroyed.

活动销毁时将触发此函数。

Common scenarios: A new activity starts and the current activity is killed. For example, pressing back button to exit the application.

常见情况 :新活动开始,当前活动被终止。 例如,按返回按钮退出应用程序。

(7. onRestart())

This function gets triggered whenever the activity starts after being stopped. It differs from onStart() in the fact that it won’t be called when the activity launches for the first time. In the later stages, it’ll always be called before onStart().

停止活动后,只要活动开始,就会触发此功能。 它与onStart()不同之处在于,在活动首次启动时不会调用它。 在后面的阶段中,将始终在onStart()之前onStart()它。





(Saving and Restoring Activity States)

Android provides us with a pair of functions : onSaveInstanceState() and onRestoreInstanceState().

Android为我们提供了一对函数: onSaveInstanceState()onRestoreInstanceState()

Following are the major scenarios when your activity’s state is saved.

以下是保存活动状态的主要方案。

  1. When onStop() is triggered. 触发onStop()
  2. On configuration changes such as screen rotations, changes in screen sizes. Android N has multi-window features, so user often changes the window size of the applications.

Configuration changes generally trigger the application to recreate the current activity by destroying the current view to draw it again. We need to save the current state of the activity in the onSaveInstanceState() function as shown below.

配置更改通常会通过破坏当前视图以再次绘制来触发应用程序重新创建当前活动。 我们需要将活动的当前状态保存在onSaveInstanceState()函数中,如下所示。

override fun onSaveInstanceState(outState: Bundle?) {
        super.onSaveInstanceState(outState)
    }

The Bundle object stores the field values from the activity in the form of key/value pairs.

Bundle对象以键/值对的形式存储活动中的字段值。

The Bundle object is of the type nullable to prevent NullPointerException, thanks to Kotlin.

由于Kotlin,Bundle对象的类型可以为null,以防止NullPointerException。

override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
        super.onRestoreInstanceState(savedInstanceState)
}

The onRestoreInstanceState() function is only called when a saved state exists.

仅当存在保存状态时才调用onRestoreInstanceState()函数。

Note: Android automatically takes care of saving and restoring Views that have a unique ID.

注意 :Android会自动负责保存和还原具有唯一ID的视图。

Hence in the below layout, only the value of TextView would be saved and restored.

因此,在下面的布局中,将仅保存和恢复TextView的值。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="net.androidly.helloworldkotlin.MainActivity">

    <TextView
        android:id="@+id/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" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CLICK ME"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</android.support.constraint.ConstraintLayout>

To disable saving the view’s state, set the attribute android:saveEnabled to false

要禁用保存视图的状态,请将属性android:saveEnabledfalse

For Custom Views we need to explicitly set setSavedEnabled(true) on the widget.

对于自定义视图,我们需要在小部件上显式设置setSavedEnabled(true)

Following code snippet demonstrates saving and restoring state in an activity.

以下代码段演示了活动中的保存和恢复状态。

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {


    var title = "This title variable would reset when the configuration is changed. Let's preserve it"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        textView.setText(title)
    }

    override fun onSaveInstanceState(outState: Bundle?) {
        outState?.putString("title",title)
        super.onSaveInstanceState(outState)
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
        textView.setText(savedInstanceState?.getString("title"))
        super.onRestoreInstanceState(savedInstanceState)
    }
}

The onRestoreInstanceState() function is called only when recreating activity after it was killed by the Android OS.

onRestoreInstanceState()函数仅在被Android OS杀死活动后重新创建活动时才调用。

Note: Alternatively, the saved instance values can be retrieved in the onCreate function too. But we’ll have to keep a null checker since the bundle object would be null when the activity is created for the first time.

注意 :或者,也可以在onCreate函数中检索保存的实例值。 但是我们必须保留一个null检查器,因为在首次创建活动时,bundle对象将为null。

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (savedInstanceState != null) {
            textView.setText(savedInstanceState.getString("title"))
        } else
            textView.setText(title)
    }

(Handling Activity Configuration Changes Ourselves)

We can set the android:configChanges attribute in the AndroidManifest.xml file to prevent recreating the activity on a configuration change.

我们可以在AndroidManifest.xml文件中设置android:configChanges属性,以防止在配置更改时重新创建活动。

<activity android:name=".MainActivity"
          android:configChanges="orientation|keyboardHidden|screenSize"
          android:label="@string/app_name">

The following method gets triggered whenever any of the above configuration change happens.

每当上述任何配置更改发生时,都会触发以下方法。

override fun onConfigurationChanged(newConfig: Configuration?) {
        super.onConfigurationChanged(newConfig)
}

References: Google Docs

参考资料: Google文件

翻译自: https://www.journaldev.com/53/android-activity-lifecycle

android生命周期