[Andriod官方训练教程]管理Activity的生命活动之重新创建一个Activity

原文地址:https://developer.android.com/training/basics/activity-lifecycle/recreating.html

-----------------------------------------------------------------------------------------------------------------------

There are a few scenarios in which your activity is destroyed due to normal app behavior, such as when the user presses theBack 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.

有一些情况下你的activity因为正常的app行为而被销毁,例如当用户按下返回按钮或者你的activity调用了finish()预示着它本身的销毁。如果你的activity当前是停止状态并且在很长时间内没有被使用,或者前台的activity需要更多的资源因此系统需要关闭后台程序来回收内存,系统都有可能会销毁你的activity。

When your activity is destroyed because the user presses Back or the activity finishes itself, the system's concept of thatActivity 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.

当你的activity因为用户按下返回按钮而自己销毁时,系统中的Activity实例会永久消失,因为这样的行为表明activity不再被需要了。但是,如果系统销毁activity是因为系统约束(而不是正常的app行为),那么尽管真正的Activity实例已经消失,系统仍然记得它的存在,这样当用户导航回到它时,系统将使用保存的数据(表述了activity销毁时的状态)来创建一个新的activity实例。系统用于重新载入之前状态的保存的数据被叫做“实例状态”,它是一个存储在一个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).

警告:每次用户旋转屏幕时,你的activity将会被销毁然后再重建。当屏幕改变方向时,系统销毁并重建前台的activity,因为屏幕的设置发生了变化而你的activity可能需要加载另一些资料(例如布局)。

By default, the system uses the Bundle instance state to save information about eachView object in your activity layout (such as the text value entered into anEditText 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实例状态来保存你的activity布局(例如输入到EditText对象中的文本值)中的每个View的相关信息。因此,如果你的activity实例被销毁再被重建后,布局的状态会被重新载入为它之前的状态而不需要你编写任何代码。但是,你的activity可能需要你想要载入的更多的信息,例如activity中追踪用户进程的成员变量。

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系统重载你的activity中views的状态,每一个view都必须有一个唯一的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 theBundle 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 sameBundle object to both theonRestoreInstanceState() andonCreate() methods.

为了保存额外的有关activity状态的数据,你必须重载onSaveInstanceState()回调方法。当用户准备离开你的activity时系统将调用这个方法,并将它传递给Bundle对象以便你的activity意外销毁时可以被保存。

Figure 2. As the system begins to stop your activity, it callsonSaveInstanceState() (1) so you can specify additional state data you'd like to save in case theActivity 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 theonCreate() method (2) and theonRestoreInstanceState() method (3).

图2. 当系统开始停止你的activity时,它调用onSaveInstanceState() (1),因此万一Activity实例必须被重建时你可以指明你想抱保存的额外状态。如果activity被销毁并且一个相同的实例必须被重建,系统将(1)中定义的状态传递给onCreate() 方法 (2) 以及onRestoreInstanceState()方法 (3)。

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 anEditText widget or the scroll position of aListView.

当你的activity要停止时,系统调用onSaveInstanceState(),因此你的activity可以用一个键-值对集合保存状态信息。这个方法的默认实现保存了activity中view的层级结构信息,例如EditText中的文本或是ListView中的滚动位置。

To save additional state information for your activity, you must implement onSaveInstanceState() and add key-value pairs to theBundle object. For example:

为了保存你的activity中额外的信息,你必须实现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 ofonSaveInstanceState() so the default implementation can save the state of the view hierarchy.

警告:永远调用onSaveInstanceState()的父类实现,因为默认实现可以保存view层级结构的状态。

Restore Your Activity State —— 重载你的活动状态


When your activity is recreated after it was previously destroyed, you can recover your saved state from theBundle that the system passes your activity. Both theonCreate() andonRestoreInstanceState() callback methods receive the sameBundle that contains the instance state information.

当你的activity之前被销毁再被重建时,你可以从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。如果它是null,那么系统将会创建一个新的activity实例,而不是重新载入之前被销毁的一个。

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 implementonRestoreInstanceState(), which the system calls after theonStart() method. The system callsonRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether theBundle is null:

你可能选择去实现onRestoreInstanceState()(系统在onStart()方法后调用)而不是在onCreate()重新载入状态。系统仅在有某个保存的状态需要被重载时才调用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 ofonRestoreInstanceState() so the default implementation can restore the state of the view hierarchy.

警告:永远先调用onRestoreInstanceState()的父类实现,因为默认实现可以重新载入view层级结构的状态。

To learn more about recreating your activity due to a restart event at runtime (such as when the screen rotates), readHandling Runtime Changes.

想要学习更多的关于在运行时刻重启事件发生时重建你的activity,请阅读Handling Runtime Changes

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值