(三)Managing the Activity Lifecycle管理activity的生命周期

本文首次发表于依鹏CSDN博客,转载请注明出处:http://blog.csdn.net/m0_37240709/article/details/77171529


Managing the Activity Lifecycle管理activity的生命周期


As a user navigates through, out of, and back to your app, the Activity instances in your app transition between different states in their lifecycle. For instance, when your activity starts for the first time, it comes to the foreground of the system and receives user focus. During this process, the Android system calls a series of lifecycle methods on the activity in which you set up the user interface and other components. If the user performs an action that starts another activity or switches to another app, the system calls another set of lifecycle methods on your activity as it moves into the background (where the activity is no longer visible, but the instance and its state remains intact).
当用户浏览、退出以及再返回你的应用时,应用程序中的Activity实例会在不同的状态之间切换。例如,当您的Activity第一次启动时,它会出现在系统的前台,并接收用户的焦点。在这个过程中,Android系统调用了Activity的一系列的生命周期方法,这个Activity就是您设置了用户界面和其他组件的Activity。如果用户执行一个动作,如启动另一个Activity或切换到另一个应用程序,系统就会在活动中调用另一组生命周期方法,将它转到后台(活动不再可见,但实例及其状态仍然完整)。
Within the lifecycle callback methods, you can declare how your activity behaves when the user leaves and re-enters the activity. For example, if you're building a streaming video player, you might pause the video and terminate the network connection when the user switches to another app. When the user returns, you can reconnect to the network and allow the user to resume the video from the same spot.
在生命周期回调方法中,当用户离开并重新进入activity时,您可以声明activity的行为。例如,如果你正在构建一个流媒体视频播放器,当用户切换到另一个应用程序时,你可能会暂停视频并终止网络连接,当用户返回时,你可以重新连接到网络,允许用户从同一地点重新开始视频。
This class explains important lifecycle callback methods that each Activity instance receives and how you can use them so your activity does what the user expects and does not consume system resources when your activity doesn't need them.

本次课程解释了每个Activity实例接收到的重要的生命周期回调方法,以及如何使用它们,这样您的Activity就可以满足用户的期望,并且当您的Activity不需要这些方法时,它不会消耗系统资源。


1、Starting an Activity启动Activity

Unlike other programming paradigms in which apps are launched with a main() method, the Android system initiates code in an Activity instance by invoking specific callback methods that correspond to specific stages of its lifecycle. There is a sequence of callback methods that start up an activity and a sequence of callback methods that tear down an activity.
与其他应用程序以main()方法启动的编程范例不同,Android系统通过调用特定的回调方法来在Activity实例中启动代码,该方法对应于其生命周期的特定阶段。这里有一系列启动activity的回调方法,和一系列销毁activity的回调方法。
This lesson provides an overview of the most important lifecycle methods and shows you how to handle the first lifecycle callback that creates a new instance of your activity.
这个课程提供了对最重要的生命周期方法的概述,并向您展示了如何处理创建一个activity实例的第一个生命周期回调。

1.1、Understand the Lifecycle Callbacks理解生命周期回调

During the life of an activity, the system calls a core set of lifecycle methods in a sequence similar to a step pyramid. That is, each stage of the activity lifecycle is a separate step on the pyramid. As the system creates a new activity instance, each callback method moves the activity state one step toward the top. The top of the pyramid is the point at which the activity is running in the foreground and the user can interact with it.
在activity的生命周期中,系统以类似于一个阶梯金字塔的顺序调用一组核心的生命周期方法。也就是说,activity生命周期的每个阶段都是金字塔的一个单独的梯级。当系统创建一个新的活动实例时,每个回调方法将activity的状态向顶端移动一步。金字塔的顶部是activity在前台运行的时候,用户可以与它进行交互。
As the user begins to leave the activity, the system calls other methods that move the activity state back down the pyramid in order to dismantle the activity. In some cases, the activity will move only part way down the pyramid and wait (such as when the user switches to another app), from which point the activity can move back to the top (if the user returns to the activity) and resume where the user left off.
当用户开始离开该activity时,系统调用其他方法,将activity的状态向下逐渐移出金字塔,以解除activity。在某些情况下,activity只会沿着金字塔向下移动一部分,而后等待(比如当用户切换到另一个应用程序时),从这一点开始,activity还可以回到顶部(如果用户返回到活动中),并恢复到用户之前离开的位置。


Figure 1. A simplified illustration of the Activity lifecycle, expressed as a step pyramid. This shows how, for every callback used to take the activity a step toward the Resumed state at the top, there's a callback method that takes the activity a step down. The activity can also return to the resumed state from the Paused and Stopped state.
图1所示。一个简化的activity生命周期的图例,表示为一个阶梯型金字塔。这表明,前面的回调方法逐步使activity的状态达到金字塔顶端的恢复状态,而后面的方法逐步将状态从金字塔顶端降下来。activity还可以从暂停状态和停止状态返回到恢复状态。

Depending on the complexity of your activity, you probably don't need to implement all the lifecycle methods. However, it's important that you understand each one and implement those that ensure your app behaves the way users expect. Implementing your activity lifecycle methods properly ensures your app behaves well in several ways, including that it:
根据您的activity的复杂性,您可能不需要实现所有的生命周期方法。然而,重要的是你要理解每一个方法,实现那些确保你的应用程序按照用户期望的方式运行的方法。恰当的实现activity的生命周期方法确保您的应用程序在以下几个方面表现良好:
  • Does not crash if the user receives a phone call or switches to another app while using your app. 如果用户中途接听电话或切换到其他应用,你的应用程序不能崩溃。
  • Does not consume valuable system resources when the user is not actively using it. 当用户没有使用它时,不要消耗有珍贵的系统资源
  • Does not lose the user's progress if they leave your app and return to it at a later time. 当用户离开而后返回你的应用时,不能失去用户之前的使用数据。
  • Does not crash or lose the user's progress when the screen rotates between landscape and portrait orientation.屏幕横竖屏切换时应用不能挂掉或者丢失用户数据

As you'll learn in the following lessons, there are several situations in which an activity transitions between different states that are illustrated in figure 1. However, only three of these states can be static. That is, the activity can exist in one of only three states for an extended period of time:
正如您将在下面的课程中学习到的,有这么几种情况,activity在图1所示的不同状态间切换。然而,这些状态中只有三个可以稳定存在的。也就是说, activity可以在很长一段时间内保持在三种状态上:
Resumed恢复状态(运行状态)
In this state, the activity is in the foreground and the user can interact with it. (Also sometimes referred to as the "running" state.)
在这个状态中,activity处于前台,用户可以与它进行交互。(有时也被称为“运行”状态)。
Paused暂停状态
In this state, the activity is partially obscured by another activity—the other activity that's in the foreground is semi-transparent or doesn't cover the entire screen. The paused activity does not receive user input and cannot execute any code.
在这种状态下,activity被另一个activity部分掩盖——在前台的那个activity是半透明的,或者不覆盖整个屏幕。处于暂停状态的activity不能接收用户的输入,也不能执行任何代码。
Stopped停止状态
In this state, the activity is completely hidden and not visible to the user; it is considered to be in the background. While stopped, the activity instance and all its state information such as member variables is retained, but it cannot execute any code.
在这种状态下,activity是完全隐藏的,对用户来说是不可见的;它被认为是处于后台中。停止时,activity实例及其所有的状态信息,如成员变量都被保留,但是它不能执行任何代码。
The other states (Created and Started) are transient and the system quickly moves from them to the next state by calling the next lifecycle callback method. That is, after the system calls onCreate(), it quickly calls onStart(), which is quickly followed by onResume().
其他状态(创建和启动)是临时的,系统通过调用下一个生命周期回调方法快速地从它们转移到下一个状态。也就是说,在系统调用onCreate()之后,它会快速调用onStart(),而后很快就会调用onResume()。
That's it for the basic activity lifecycle. Now you'll start learning about some of the specific lifecycle behaviors.
这就是基本活动生命周期的情况。现在,您将开始学习一些特定的生命周期行为。

1.2、Specify Your App's Launcher Activity指定应用程序的启动Activity

When the user selects your app icon from the Home screen, the system calls the onCreate() method for the Activity in your app that you've declared to be the "launcher" (or "main") activity. This is the activity that serves as the main entry point to your app's user interface.
当用户从主屏幕选择应用程序图标时,系统会调用你应用程序中声明为启动activity的onCreate()方法。这是作为应用程序用户界面的主入口点的activity。
You can define which activity to use as the main activity in the Android manifest file, AndroidManifest.xml, which is at the root of your project directory.
你可以在清单文件中指定哪个activity作为主activity,清单文件就在项目的根目录下。
The main activity for your app must be declared in the manifest with an <intent-filter> that includes the MAIN action and LAUNCHER category. For example:
应用程序的主activity必须在manifest中声明,它包含了MAIN action和LAUNCHER项。例如:
<activity android:name=".MainActivity" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Note: When you create a new Android project with the Android SDK tools, the default project files include an Activity class that's declared in the manifest with this filter.
注意:当你用Android SDK工具创建一个新的Android项目时,默认的项目文件包含一个Activity类,这个类在清单中被声明,声明中带有filter。
If either the MAIN action or LAUNCHER category are not declared for one of your activities, then your app icon will not appear in the Home screen's list of apps.
如果应用中所有activity都没被声明主动作或启动项,那么你的应用图标将不会出现在主屏幕的应用列表中。

1.3、Create a New Instance创建一个新实例

Most apps include several different activities that allow the user to perform different actions. Whether an activity is the main activity that's created when the user clicks your app icon or a different activity that your app starts in response to a user action, the system creates every new instance of Activity by calling its onCreate() method.
大多数应用程序包括几个不同的activity,允许用户执行不同的操作。无论activity是用户单击app图标时创建的主activity,还是应用程序在响应用户操作时启动的activity,系统都会通过调用onCreate()方法创建每个activity的新实例。
You must implement the onCreate() method to perform basic application startup logic that should happen only once for the entire life of the activity. For example, your implementation of onCreate() should define the user interface and possibly instantiate some class-scope variables.
您必须实现onCreate()方法来执行基本的应用程序启动逻辑,该逻辑在activity的整个生命周期中只会发生一次。例如,在实现的onCreate()方法中定义用户接口或实例化一些静态变量。
For example, the following example of the onCreate() method shows some code that performs some fundamental setup for the activity, such as declaring the user interface (defined in an XML layout file), defining member variables, and configuring some of the UI.
例如,在下面的例子中的onCreate()方法里展示了一些代码,这些代码对activity进行了一些基本的配置,比如声明用户界面(定义在XML布局文件中),定义成员变量,以及配置一些UI。
// Member variable for text view in the layout布局中的文本视图的成员变量
TextView mTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    // Set the user interface layout for this Activity为该活动设置用户界面布局
    // The layout file is defined in the project res/layout/main_activity.xml file
    //布局文件定义在项目的res/layout/main_activity.xml文件
    setContentView(R.layout.main_activity);
    
    // Initialize member TextView so we can manipulate it later
    //初始化成员变量TextView,这样我们就可以对它进行操作了
    mTextView = (TextView) findViewById(R.id.text_message);
    
    // Make sure we're running on Honeycomb or higher to use ActionBar APIs
    //确保我们运行在Honeycomb或者更高的版本中使用ActionBar
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // For the main activity, make sure the app icon in the action bar
        // does not behave as a button
        //对于主活动,要确保工具栏中的应用图标不能成为一个按钮
        ActionBar actionBar = getActionBar();
        actionBar.setHomeButtonEnabled(false);
    }
}

Caution: Using the SDK_INT to prevent older systems from executing new APIs works in this way on Android 2.0 (API level 5) and higher only. Older versions will encounter a runtime exception.
注意:使用SDK_INT防止旧系统执行新API,仅能在Android 2.0(API level 5)或更高的系统版本上工作。较老的版本将会遇到运行时异常。
Once the onCreate() finishes execution, the system calls the onStart() and onResume() methods in quick succession. Your activity never resides in the Created or Started states. Technically, the activity becomes visible to the user when onStart() is called, but onResume() quickly follows and the activity remains in the Resumed state until something occurs to change that, such as when a phone call is received, the user navigates to another activity, or the device screen turns off.
一旦onCreate()完成了执行,系统就会快速地调用onStart()和onResume()方法。activity从不驻留在创建或启动的状态中。从技术上讲,当调用onStart()时,用户可以看到该活动,但是onResume()很快就会出现,并且activity保持在恢复状态,直到发生了一些变化,比如接收到一个电话,用户跳转到另一个activity,或者设备屏幕关闭。
In the other lessons that follow, you'll see how the other start up methods, onStart() and onResume(), are useful during your activity's lifecycle when used to resume the activity from the Paused or Stopped states.
在接下来的其他课程中,您将看到其他启动方法,onStart()和onResume(),在activity的生命周期中,从暂停或停止状态恢复活动时非常有用。
Note: The onCreate() method includes a parameter called savedInstanceState that's discussed in the latter lesson about Recreating an Activity.
注意:onCreate()方法包括一个名为savedInstanceState的参数,这将在后面的课程“重建activity”中讨论。

Figure 2. Another illustration of the activity lifecycle structure with an emphasis on the three main callbacks that the system calls in sequence when creating a new instance of the activity: onCreate(), onStart(), and onResume(). Once this sequence of callbacks complete, the activity reaches the Resumed state where users can interact with the activity until they switch to a different activity.
图2。activity生命周期结构的另一个图例,重点是在创建activity的新实例时,系统调用的三个主回调:onCreate()、onStart()和onResume()。一旦这个回调序列完成,该activity就会到达恢复状态,用户可以与该activity进行交互,直到跳转到不同的activity。

1.4、Destroy the Activity销毁activity

While the activity's first lifecycle callback is onCreate(), its very last callback is onDestroy(). The system calls this method on your activity as the final signal that your activity instance is being completely removed from the system memory.
activity的第一个生命周期回调是onCreate()方法,它的最后一个回调是onDestroy()方法。系统调用activity此方法作为activity实例完全从系统内存中删除的最终信号。
Most apps don't need to implement this method because local class references are destroyed with the activity and your activity should perform most cleanup during onPause() and onStop(). However, if your activity includes background threads that you created during onCreate() or other long-running resources that could potentially leak memory if not properly closed, you should kill them during onDestroy().
大多数应用程序不需要实现这种方法,因为局部类引用会被activity销毁,而您的activity应该在onPause()和onStop()中执行大部分的清理工作。但是,您的activity包括您在onCreate()或其他长时间运行的资源中创建的后台线程,如果没有适当地关闭它们可能会导致泄漏内存,那么您应该在onDestroy()中销毁它们。
@Override
public void onDestroy() {
    super.onDestroy(); // Always call the superclass总是调用父类
    
    // Stop method tracing that the activity started during onCreate()
    android.os.Debug.stopMethodTracing();
}


Note: The system calls onDestroy() after it has already called onPause() and onStop() in all situations except one: when you call finish() from within the onCreate() method. In some cases, such as when your activity operates as a temporary decision maker to launch another activity, you might call finish() from within onCreate() to destroy the activity. In this case, the system immediately calls onDestroy() without calling any of the other lifecycle methods.

注意:系统调用onDestroy()方法总是在调用onPause()方法和onStop()方法之后,除了一种情况:在onCreate()方法中调用finish()。在某些情况下,例如当您的activity作为一个临时的决策者来启动另一个activity时,您可以从onCreate()中调用finish()来销毁该activity。在这种情况下,系统立即调用onDestroy(),而不调用任何其他生命周期方法。


2、Pausing and Resuming an Activity暂停和恢复Activity

During normal app use, the app sometimes loses focus, causing the activity to pause. For example, when apps run in multi-window mode, only one of the apps has the focus at any time; the system pauses all other apps. Similarly, when a semi-transparent activity opens (such as one in the style of a dialog), the previous activity pauses. As long as the activity is still partially visible but currently not the activity in focus, it remains paused.
在正常的应用程序使用过程中,应用有时会失去焦点,导致activity暂停。例如,当应用程序以多窗口模式运行时,在任何时候都只有一个应用程序有焦点;该系统暂停了所有其他应用程序。类似地,当一个半透明的activity打开时(例如一个对话框),前一个activity暂停。只要该activity仍部分可见,但目前不是得到焦点的activity,它就会暂停。
However, once the activity is fully-obstructed and not visible, it stops (which is discussed in the next lesson).
然而,一旦活动被完全阻塞并且不可见,它就停止了(下一节将讨论这个问题)。
As your activity enters the paused state, the system calls the onPause() method on your Activity, which allows you to stop ongoing actions that should not continue while paused or persist any information that should be permanently saved in case the user continues to leave your app. If the user returns to your activity from the paused state, the system resumes it and calls the onResume() method.
当你的activity进入暂停状态,系统调用activity的onPause()方法,你应停止正在进行的行为,不应该继续而应暂停且应永久保存保存所有信息, ,以防用户离开你的应用程序。如果用户从暂停状态返回到你的activity,系统恢复它并调用onResume()方法。
Note: When the system calls your activity's onPause() method, the system may be signaling that the activity will be paused for a moment and the user may return focus to your activity, or that the app is running in multi-window mode. However, this method call may also be the first indication that the user is leaving your activity.
注意:当系统调用您的activity的onPause()方法时,系统可能发出信号,该activity将暂停一段时间,用户可能会将焦点返回到您的activity,或者该应用程序正在以多窗口模式运行。不过,这个方法的调用也是用户离开activity的第一个征兆。

Figure 1. When a semi-transparent activity obscures your activity, the system calls onPause() and the activity waits in the Paused state (1). If the user returns to the activity while it's still paused, the system calls onResume() (2).
图1所示。当一个半透明的activity遮盖了您的activity时,系统调用onPause()方法,activity在暂停状态(1)中等待,如果用户在仍然暂停的时候返回activity,系统将调用onResume() 方法(2)。
2.1、Pause Your Activity暂停activity
When the system calls onPause() for your activity, it technically means your activity is still partially visible, but most often is an indication that the user is leaving the activity and it will soon enter the Stopped state. You should usually use the onPause() callback to:
当系统为您的activity调用onPause()时,它在技术上意味着您的activity仍然是部分可见的,但是大多数情况下表明用户正在离开该activity,并且它将很快进入停止状态。您通常应该使用onPause()回调做下面的事情:
  • Check if the activity is visible; if it is not, stop animations or other ongoing actions that could consume CPU. Remember, beginning with Android 7.0, a paused app might be running in multi-window mode. In this case, you would not want to stop animations or video playback. 检查activity是否可见;如果不可见,停止动画或其他可能消耗CPU的动作。记住,从Android 7.0开始,一个暂停的应用程序可能在多窗口模式下运行。在这种情况下,您不希望停止动画或视频回放。
  • Commit unsaved changes, but only if users expect such changes to be permanently saved when they leave (such as a draft email). 提交未保存的更改,但前提是用户希望在他们离开时永久保存这些更改(如电子邮件草稿)。
  • Release system resources, such as broadcast receivers, handles to sensors (like GPS), or any resources that may affect battery life while your activity is paused and the user does not need them. 当你的activity处于暂停状态,用户不再需要他们时,释放系统资源,如广播接收器,对传感器的操控(如GPS),或任何可能影响电池寿命的资源。

For example, if your application uses the Camera, the onPause() method is a good place to release it.
例如,如果您的应用程序使用了照相机,onPause()方法是一个释放它的好地方。
@Override
public void onPause() {
    super.onPause(); // Always call the superclass method first
    
    // Release the Camera because we don't need it when paused
    // and other activities might need to use it.
    if (mCamera != null) {
        mCamera.release();
        mCamera = null;
    }
}


Generally, you should not use onPause() to store user changes (such as personal information entered into a form) to permanent storage. The only time you should persist user changes to permanent storage within onPause() is when you're certain users expect the changes to be auto-saved (such as when drafting an email). However, you should avoid performing CPU-intensive work during onPause(), such as writing to a database, because it can slow the visible transition to the next activity (you should instead perform heavy-load shutdown operations during onStop()).
通常,您不应该使用onPause()来存储用户更改(例如输入到表单中的个人信息)到固存。在onPause()中,您应该将用户更改持久存储到固存的惟一时间是当您确定用户希望自动保存更改时(例如在起草电子邮件时)。但是,您应该避免在onPause()中执行大量占用cpu资源的工作,例如写入数据库,因为它可以减缓对下一个activity的可见转换(您应该在onStop()中执行高负载关闭操作)。
You should keep the amount of operations done in the onPause() method relatively simple in order to allow for a speedy transition to the user's next destination if your activity is actually being stopped.
您应该保持onPause()方法中所做的操作的数量相对少些,以便在您的activity被停止时能够快速地转换到用户的下一个目的地。
Note: When your activity is paused, the Activity instance is kept resident in memory and is recalled when the activity resumes. You don’t need to re-initialize components that were created during any of the callback methods leading up to the Resumed state.
注意:当您的activity暂停时,activity实例将保存在内存中,并在activity恢复时被收回。您不需要重新初始化在恢复状态之前的一些回调方法中创建的组件。

2.2、Resume Your Activity恢复activity

When the user resumes your activity from the Paused state, the system calls the onResume() method.
当用户从暂停状态恢复activity时,系统将调用onResume()方法。
Be aware that the system calls this method every time your activity comes into the foreground, including when it's created for the first time. As such, you should implement onResume() to initialize components that you release during onPause() and perform any other initializations that must occur each time the activity enters the Resumed state (such as begin animations and initialize components only used while the activity has user focus).
请注意,每当activity进入前台时,系统都会调用该方法,包括第一次创建activity时。因此,您应该实现onResume()来初始化您在onPause()中释放的组件,并执行activity进入恢复状态时必须进行的其他初始化(例如,只有在activity具有用户焦点时才开始使用动画和初始化组件)。
The following example of onResume() is the counterpart to the onPause() example above, so it initializes the camera that's released when the activity pauses.
下面的onResume()示例与上面的onPause()示例相对应,因此它初始化了在activity暂停时释放的照像机。
@Override
public void onResume() {
    super.onResume(); // Always call the superclass method first
    
    // Get the Camera instance as the activity achieves full user focus
    if (mCamera == null) {
        initializeCamera(); // Local method to handle camera init
    }

}


3、Stopping and Restarting an Activity停止并重新启动活动

Properly stopping and restarting your activity is an important process in the activity lifecycle that ensures your users perceive that your app is always alive and doesn't lose their progress. There are a few of key scenarios in which your activity is stopped and restarted:
正确地停止和重新启动您的活动是活动生命周期中的一个重要过程,它可以确保您的用户认为您的应用程序始终是活着的,并且不会丢失它们的进展。这里有一些您的活动被停止并重新启动的关键场景:
  • The user opens the Recent Apps window and switches from your app to another app. The activity in your app that's currently in the foreground is stopped. If the user returns to your app from the Home screen launcher icon or the Recent Apps window, the activity restarts. 用户打开了最近的应用窗口,从你的应用切换到另一个应用。你的应用程序当前处于前台的活动停止了。如果用户从主屏幕启动图标或最近的应用程序窗口返回到您的应用程序,活动将重新启动。
  • The user performs an action in your app that starts a new activity. The current activity is stopped when the second activity is created. If the user then presses the Back button, the first activity is restarted. 用户在应用程序中执行一个动作,启动一个新的活动。当创建第二个活动时,当前活动将停止。如果用户按下返回按钮,第一个活动将重新启动。
  • The user receives a phone call while using your app on his or her phone. 用户在手机上使用你的应用时,会收到一个电话。

The Activity class provides two lifecycle methods, onStop() and onRestart(), which allow you to specifically handle how your activity handles being stopped and restarted. Unlike the paused state, which identifies a partial UI obstruction, the stopped state guarantees that the UI is no longer visible and the user's focus is in a separate activity (or an entirely separate app).
Activity类提供了两个生命周期方法,onStop()和onRestart(),它允许您特别地操纵您的活动,当它被停止和重新启动时要怎样处理。与暂停状态不同,它标识了部分UI阻塞,停止状态保证UI不再可见,用户的注意力集中在一个单独的活动(或一个完全独立的应用程序)上。
Note: 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.
注意:因为系统在系统内存中保留您的活动实例,所以您根本不需要实现onStop()和onRestart() (甚至onStart()方法)。对于大多数的活动都是相对简单的,活动将很好的停止并重新启动,您可能只需要使用onPause()来暂停正在进行的操作,并断开系统资源的连接。

Figure 1. When the user leaves your activity, the system calls onStop() to stop the activity (1). If the user returns while the activity is stopped, the system calls onRestart() (2), quickly followed by onStart() (3) and onResume() (4). Notice that no matter what scenario causes the activity to stop, the system always calls onPause() before calling onStop().
图1所示。当用户离开你的活动,系统调用原onStop ()(1)停止活动。如果用户从活动停止状态返回,系统调用onRestart()(2),紧接着onStart()(3)和onResume()(4)。注意,不管什么情况导致活动停止,系统总是在调用onStop()之前调用onPause()。

3.1、Stop Your Activity停止活动

When your activity receives a call to the onStop() method, it's no longer visible and should release almost all resources that aren't needed while the user is not using it. Once your activity is stopped, the system might destroy the instance if it needs to recover system memory. In extreme cases, the system might simply kill your app process without calling the activity's final onDestroy() callback, so it's important you use onStop() to release resources that might leak memory.
当您的活动收到一个对onStop()方法的调用时,它将不再可见,并且应该在用户不使用它的时候释放几乎所有不需要的资源。一旦停止活动,如果系统需要恢复系统内存就可能会销毁实例。在极端情况下,系统可能会在不调用活动的最终onDestroy()回调的情况下杀死应用程序进程,因此使用onStop()来释放可能泄露内存的资源是很重要的。
Although the onPause() method is called before onStop(), you should use onStop() to perform larger, more CPU intensive shut-down operations, such as writing information to a database.
尽管onPause()方法在onStop()之前被调用,但是您应该使用onStop()来执行大量的或较占用CPU的关闭操作,比如向数据库写入信息。
For example, here's an implementation of onStop() that saves the contents of a draft note to persistent storage:
例如,这里有一个onStop()的实现,它将草稿的内容保存到固定存储器中:
@Override
protected void onStop() {
    super.onStop(); // Always call the superclass method first
    
    // Save the note's current draft, because the activity is stopping
    // and we want to be sure the current note progress isn't lost.
    ContentValues values = new ContentValues();
    values.put(NotePad.Notes.COLUMN_NAME_NOTE, getCurrentNoteText());
    values.put(NotePad.Notes.COLUMN_NAME_TITLE, getCurrentNoteTitle());
    
    getContentResolver().update(
        mUri, // The URI for the note to update.
        values, // The map of column names and new values to apply to them.
        null, // No SELECT criteria are used.
        null // No WHERE columns are used.
    );
}

When your activity is stopped, the Activity object is kept resident in memory and is recalled when the activity resumes. You don’t need to re-initialize components that were created during any of the callback methods leading up to the Resumed state. The system also keeps track of the current state for each View in the layout, so if the user entered text into an EditText widget, that content is retained so you don't need to save and restore it.
当停止活动时,活动对象将驻留在内存中,并在活动恢复时被收回。您不需要重新初始化在恢复状态之前的一些回调方法中创建的组件。该系统还会跟踪布局中的每个视图的当前状态,因此如果用户将文本输入到EditText小部件中,那么该内容将被保留,因此您不需要保存和恢复它。
Note: Even if the system destroys your activity while it's stopped, it still retains the state of the View objects (such as text in an EditText) in a Bundle (a blob of key-value pairs) and restores them if the user navigates back to the same instance of the activity (the next lesson talks more about using a Bundle to save other state data in case your activity is destroyed and recreated).
注意:即使系统销毁了你的活动在它处于停止状态时,它仍然在Bundle (键-值对型Blob对象)中保留了视图对象的状态(比如EditText中的文本),如果用户回到相同的实例的活动便可以恢复它(下节课会谈更多关于使用Bundle保存其他状态数据,以防你的活动被销毁并重新创建)。

3.2、Start/Restart Your Activity启动/重新启动活动

When your activity comes back to the foreground from the stopped state, it receives a call to onRestart(). The system also calls the onStart() method, which happens every time your activity becomes visible (whether being restarted or created for the first time). The onRestart() method, however, is called only when the activity resumes from the stopped state, so you can use it to perform special restoration work that might be necessary only if the activity was previously stopped, but not destroyed.
当您的活动从停止状态返回到前台时,它将收到一个对onRestart()的调用。每当您的活动变为可见时(或重新启动或第一次创建),该系统还调用onStart()方法。然而,onRestart()方法仅在活动从停止状态恢复时才被调用,仅在活动被停止而不是被销毁时,您可以使用它来执行专门的的恢复工作。
It's uncommon that an app needs to use onRestart() to restore the activity's state, so there aren't any guidelines for this method that apply to the general population of apps. However, because your onStop() method should essentially clean up all your activity's resources, you'll need to re-instantiate them when the activity restarts. Yet, you also need to instantiate them when your activity is created for the first time (when there's no existing instance of the activity). For this reason, you should usually use the onStart() callback method as the counterpart to the onStop() method, because the system calls onStart() both when it creates your activity and when it restarts the activity from the stopped state.
应用程序需要使用onRestart ()来恢复活动状态,这是不常见的,因此这种方法并没有应用于一般程序的指导原则。但是,因为onStop()方法应该清理所有活动的资源,所以在活动重新启动时需要重新实例化它们。但是,您还需要在第一次创建活动时实例化它们(当没有活动的实例时)。由于这个原因,您通常应该使用onStart()回调方法作为onStop()方法的对应,因为当创建活动和从停止状态重新启动活动时,系统会调用onStart()。
For example, because the user might have been away from your app for a long time before coming back it, the onStart() method is a good place to verify that required system features are enabled:
例如,由于用户在返回应用程序之前可能已经离开了您的应用程序很长时间,onStart()方法是验证所需系统特性的一个好地方:
@Override
protected void onStart() {
     super.onStart(); // Always call the superclass method first

     // The activity is either being restarted or started for the first time
     // so this is where we should make sure that GPS is enabled
     LocationManager locationManager =
     (LocationManager) getSystemService(Context.LOCATION_SERVICE);
     boolean gpsEnabled = locationManager
                     .isProviderEnabled(LocationManager.GPS_PROVIDER);

     if (!gpsEnabled) {
         // Create a dialog here that requests the user to enable GPS,
         // and use an intent with the
         // android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS action
         // to take the user to the Settings screen to enable GPS when they click "OK"
     }
}
    
@Override
    protected void onRestart() {
    super.onRestart(); // Always call the superclass method first
    
    // Activity being restarted from stopped state
}

When the system destroys your activity, it calls the onDestroy() method for your Activity. Because you should generally have released most of your resources with onStop(), by the time you receive a call to onDestroy(), there's not much that most apps need to do. This method is your last chance to clean out resources that could lead to a memory leak, so you should be sure that additional threads are destroyed and other long-running actions like method tracing are also stopped.

当系统销毁您的活动时,它会调用您的活动的onDestroy()方法。因为您通常会在onStop()中释放大部分资源,当您接到onDestroy()的调用时,应用程序需要做的并不多。这个方法是您清除可能导致内存泄漏的资源的最后机会,因此您应该确保其他线程以及一些长期运行的操作被销毁,例如方法跟踪也应被停止。


4、Recreating an Activity重新创建活动

There are a few scenarios in which your activity is destroyed due to normal app behavior, such as when the user presses the Back button or your activity signals its own destruction by calling finish(). The system may also destroy your activity if it's currently stopped and hasn't been used in a long time or the foreground activity requires more resources so the system must shut down background processes to recover memory.
在一些场景中,您的活动由于正常的应用程序行为而被销毁,例如当用户按下后退按钮时,或者您的活动通过调用finish()来发出自己的销毁信号。如果系统当前停止,并且在很长一段时间内没有使用,或者前台活动需要更多的资源,那么系统必须关闭后台进程来恢复内存,系统也可能会销毁您的活动。
When your activity is destroyed because the user presses Back or the activity finishes itself, the system's concept of that Activity instance is gone forever because the behavior indicates the activity is no longer needed. However, if the system destroys the activity due to system constraints (rather than normal app behavior), then although the actual Activity instance is gone, the system remembers that it existed such that if the user navigates back to it, the system creates a new instance of the activity using a set of saved data that describes the state of the activity when it was destroyed. The saved data that the system uses to restore the previous state is called the "instance state" and is a collection of key-value pairs stored in a Bundle object.
当您的活动被破坏,由于用户按下返回键或活动结束自己时,系统的中的活动实例将永远消失,因为这种行为表明系统不再需要这个活动。然而, 如果系统因为系统约束而销毁了活动(而不是正常的应用程序行为),那么尽管实际的活动实例消失了,如果用户导航回它系统还记得它曾存在, 系统使用一组保存的数据来创建活动的新实例,这些数据描述了被销毁的活动状态。系统用来恢复前一个状态的保存数据称为“实例状态”,它是存储在一个Bundle对象中的键值对的集合。
Caution: Your activity will be destroyed and recreated each time the user rotates the screen. When the screen changes orientation, the system destroys and recreates the foreground activity because the screen configuration has changed and your activity might need to load alternative resources (such as the layout).
注意:每次用户旋转屏幕时,您的活动将被销毁并重新创建。当屏幕改变方向时,系统会销毁并重新创建前台活动,因为屏幕配置发生了变化,您的活动可能需要加载其他替换资源(比如布局)。
By default, the system uses the Bundle instance state to save information about each View object in your activity layout (such as the text value entered into an EditText object). So, if your activity instance is destroyed and recreated, the state of the layout is restored to its previous state with no code required by you. However, your activity might have more state information that you'd like to restore, such as member variables that track the user's progress in the activity.
默认情况下,系统使用Bundle实例状态来保存活动布局中的每个视图对象的信息(比如EditText对象中的文本值)。因此,如果您的活动实例被销毁并重新创建,那么布局的状态就会恢复到以前的状态,而不包含您所需要的代码。但是,您的活动可能会有更多您想要恢复的状态信息,比如在活动中跟踪用户的进展的成员变量。
Note: In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.
注意:为了让Android系统恢复活动中的视图状态,每个视图必须有一个惟一的ID,由Android:ID属性提供。
To save additional data about the activity state, you must override the onSaveInstanceState() callback method. The system calls this method when the user is leaving your activity and passes it the Bundle object that will be saved in the event that your activity is destroyed unexpectedly. If the system must recreate the activity instance later, it passes the same Bundle object to both the onRestoreInstanceState() and onCreate() methods.
要保存关于活动状态的其他数据,必须覆盖onSaveInstanceState()回调方法。当用户离开您的活动时,系统将调用该方法,并传递在您的活动被意外地销毁时保存的Bundle对象。如果系统必须稍后重新创建活动实例,那么它将把同一个Bundle对象传递给onRestoreInstanceState()和onCreate()方法。

Figure 2. As the system begins to stop your activity, it calls onSaveInstanceState() (1) so you can specify additional state data you'd like to save in case the Activity instance must be recreated. If the activity is destroyed and the same instance must be recreated, the system passes the state data defined at (1) to both the onCreate() method (2) and the onRestoreInstanceState() method (3).
图2。当系统开始停止您的活动时,它调用onSaveInstanceState()(1),这样您就可以指定您想要保存的额外的状态数据,以防活动实例必须被重新创建。如果活动被销毁,并且必须重新创建相同的实例,系统会把在(1)中定义的状态数据传递给onCreate()方法(2)和onRestoreeinstancestate()方法(3)。

4.1、Save Your Activity State保存活动状态

As your activity begins to stop, the system calls onSaveInstanceState() so your activity can save state information with a collection of key-value pairs. The default implementation of this method saves information about the state of the activity's view hierarchy, such as the text in an EditText widget or the scroll position of a ListView.
当您的活动开始停止时,系统将调用onSaveInstanceState(),这样您的活动就可以通过一个键-值对来保存状态信息。该方法的默认实现保存了活动视图层的状态信息,比如EditText小部件中的文本或ListView的滚动位置。
To save additional state information for your activity, you must implement onSaveInstanceState() and add key-value pairs to the Bundle object. For example:
要为您的活动保存额外的状态信息,您必须实现onSaveInstanceState()并将键-值对添加到Bundle对象中。例如:
static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

Caution: Always call the superclass implementation of onSaveInstanceState() so the default implementation can save the state of the view hierarchy.
警告:总是调用onSaveInstanceState()的父类实现,因此默认实现可以保存视图层的状态。

4.2、Restore Your Activity State恢复活动状态

When your activity is recreated after it was previously destroyed, you can recover your saved state from the Bundle that the system passes your activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.
当活动被销毁之后重新创建时,可以从系统传递给活动的Bundle对象中恢复保存的状态。onCreate()和onRestoreInstanceState ()回调方法都接收包含实例状态信息的相同的Bundle。
Because the onCreate() method is called whether the system is creating a new instance of your activity or recreating a previous one, you must check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed.
无论系统创建一个活动的新实例,还是重新创建前一个实例,onCreate()方法都将被调用,所以必须在尝试读取Bundle之前检查它是否为空。如果它是null,那么系统将创建一个活动的新实例,而不是恢复之前被销毁的一个实例。
For example, here's how you can restore some state data in onCreate():
例如,下面是如何在onCreate()中恢复一些状态数据的方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first
    
    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    } else {
        // Probably initialize members with default values for a new instance
    }
    ...
}

Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null:
您可以选择实现onRestoreInstanceState()方法恢复状态,而不是在onCreate()中,系统在onStart()方法之后调用onRestoreInstanceState()方法。只在有保存的状态需要被恢复时,系统才会调用onRestoreInstanceState()方法,所以您不需要检查包是否为空:
public void onRestoreInstanceState(Bundle savedInstanceState) {
    // Always call the superclass so it can restore the view hierarchy
    super.onRestoreInstanceState(savedInstanceState);
    
    // Restore state members from saved instance
    mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}

Caution: Always call the superclass implementation of onRestoreInstanceState() so the default implementation can restore the state of the view hierarchy.
警告:始终调用onRestoreInstanceState ()的超类实现,这个默认实现可以恢复视图层的状态。
To learn more about recreating your activity due to a restart event at runtime (such as when the screen rotates), read Handling Runtime Changes.
要了解更多关于在运行时重新启动事件(如屏幕旋转时)导致重新创建活动的情况,请阅读处理运行时更改。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值