Android学习路线(十五)Activity生命周期——重新创建(Recreating)一个Activity

先占个位置,下次翻译~ :p

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.

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.

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.

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.

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.

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 theonRestoreInstanceState() method
(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 an EditText widget
or the scroll position of aListView.

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

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.

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 the onCreate() and onRestoreInstanceState() callback
methods receive the same Bundle that
contains the instance state information.

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.

For example, here‘s how you can restore some state data in 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:

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.

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

Android学习路线(十五)Activity生命周期——重新创建(Recreating)一个Activity,布布扣,bubuko.com

时间: 2025-01-02 13:30:55

Android学习路线(十五)Activity生命周期——重新创建(Recreating)一个Activity的相关文章

Android学习路线(五)开启另一个Activity

在完成了 上一篇课程后,你已经有了一个应用.这个应用展示了一个包含一个文本框和一个按钮的activity(一个单独的界面).在这次的课程中,你将会通过在MainActivity中添加一些代码,来让当给你点击Send按钮时能够跳转到另一个activity中. 响应Send按钮 为了响应按钮的点击事件,打开fragment_main.xml 布局文件,然后在 <Button> 元素中加入android:onClick属性: <Button     android:layout_width=&

Android学习笔记十五.深入理解fragment(三) 之《兼容多分辨率的应用》实战

深入理解fragment(三) 之<兼容多分辨率的应用>实战 在上一篇博文中介绍了如何使用Android Fragment开发适用于大屏幕应用,现在我们在上一个应用的基础上继续学习如何使用Fragment开发兼容多分辨率的应用. 1.建立/res/values-large/refs.xml引用资源文件 为了开发兼顾屏幕分辨率的应用,我们需要建立一个引用资源文件,专门用于定义各种引用项.refs.xml引用资源文件中定义了一项引用,其作用就是标明activity_book_list实际引用(@)

activity生命周期分析(两个activity之间跳转的生命周期执行顺序)

NoteMainActivity点击跳转至NoteListActivity 我们都了解: 当A界面点击进入B界面时,此时 A===onPause--->onStop B===onStart--->onResume B界面退出,A界面显示,此时 B===onPause--->onStop A===onRestart--->onStart--->onResume 问:但是,是执行A的生命周期执行完再执行B的生命周期吗?或者B的执行完再执行A的吗? 答:不.   实际是 当A界面点

Android学习(十五) 系统服务

一.常用系统服务 后台Service在系统启动时被SystemService开启 1.MountService:监听是否有SD卡安装和移除. 2.ClipboardService:提供剪切板功能. 3.PackageManagerService:提供软件包的安装移除和查看. 4.电量.网络连接状态等等. 二.调用系统Service: getSystemService()方法:Activity的一个方法,用来获取系统服务对象,传入一个字符串,返回一个系统服务对象. 三.常用的系统服务: 传入的Na

Android——Activity生命周期(转)

Activity生命周期 子曰:溫故而知新,可以為師矣.<論語> 学习技术也一样,对于技术文档或者经典的技术书籍来说,指望看一遍就完全掌握,那基本不大可能,所以我们需要经常回过头再仔细研读几遍,以领悟到作者的思想精髓. 近来回顾了一下关于Activity的生命周期,参看了相关书籍和官方文档,也有了不小的收获,对于以前的认知有了很大程度上的改善,在这里和大家分享一下. 熟悉javaEE的朋友们都了解servlet技术,我们想要实现一个自己的servlet,需要继承相应的基类,重写它的方法,这些方

Android 第六课——Activity生命周期

声明:本文转载自 http://blog.csdn.net/liuhe688/article/details/6733407 , 感觉读了这篇文章之后,对Activity又是一个更深层次的理解,所以果断手贱转载了!希望自己以后能多看看这篇文章,提升自己! 熟悉javaEE的朋友们都了解servlet技术,我们想要实现一个自己的servlet,需要继承相应的基类,重写它的方法,这些方法会在合适的时间被servlet容器调用.其实android中的Activity运行机制跟servlet有些相似之处

Android Activity 生命周期

生命周期流程图: 相信不少朋友也已经看过这个流程图了,也基本了解了Activity生命周期的几个过程,我们就来说一说这几个过程. 1.启动Activity:系统会先调用onCreate方法,然后调用onStart方法,最后调用onResume,Activity进入运行状态. 2.当前Activity被其他Activity覆盖其上或被锁屏:系统会调用onPause方法,暂停当前Activity的执行. 3.当前Activity由被覆盖状态回到前台或解锁屏:系统会调用onResume方法,再次进入运

android开发 - Activity生命周期

本章主讲Activity的生命周期 Activity整个生命周期有四种状态,7个方法,3个嵌套循环 状态: 1.  Activity/Running 活动状态 指的是当前用户正在交互的activity状态 2. Paused                  暂停状态 指的是当前activity可见,但是被吐司或者对话框遮罩时状态 3. Stopped                停止状态 指的是被新的创建的activity遮挡时的状态,它保留了之前的操作信息和状态,但是如果系统内存不够,可能

【Android】Activity生命周期研究

1. 为什么研究Activity什么周期 Activity是Android四大组件之一,是Android人必须要深刻理解的基础内容之一. 可以提高我们对相关问题的解决能力. 对一个问题如果不能深入理解,总觉得不踏实. 2. Activity生命周期详解 2.1 Activity生命周期图解 下图是Android开发官网的原图,清晰表达了Activity生命周期中每个方法所处位置及调用流程. 上图对Activity的执行流程表达很到位,但是对每个方法在执行时,我们的设备处于一种什么状态,其中注释表