In this tutorial, we’ll be discussing the two vital methods for managing the state of the application, namely onSaveInstanceState and onRestoreInstanceState.
We’ll be developing a Counter Android Application in which we’ll handle the state of the application when the configuration changes.

在本教程中,我们将讨论管理应用程序状态的两个重要方法,即onSaveInstanceStateonRestoreInstanceState
我们将开发一个Counter Android应用程序,当配置更改时,我们将在其中处理应用程序的状态。

Android生命周期 (Android Lifecycle)

Following is the lifecycle of the Activities in our application:

以下是我们应用程序中活动的生命周期:

Whenever there is a configuration change, such as rotation or application going into multi-window mode, the activity is recreated.

每当进行配置更改(例如轮换或应用程序进入多窗口模式)时,都会重新创建活动。

In this recreation, the application gets restarted and may lose data in the views if not handled properly.

在这种娱乐中,应用程序将重新启动,并且如果处理不当,可能会丢失视图中的数据。

For this there are two methods that are triggered at different stages of the lifecycle:

为此,有两种方法在生命周期的不同阶段触发:

  • onSaveInstanceStateonSaveInstanceState
  • onRestoreInstanceStateonRestoreInstanceState

They are used to save and retrieve values. The values are stored in the form of a key-value pair.
Let’s look at each of them separately.

它们用于保存和检索值。 这些值以键值对的形式存储。
让我们分别看一下它们。

onSaveInstanceState (onSaveInstanceState)

onSaveInstanceState method gets called typically before/after onStop() is called. This varies from Android version to version. In the older versions it used to get before onStop().

通常在调用onStop()之前/之后调用onSaveInstanceState方法。 视Android版本而异。 在旧版本中,它通常先于onStop()获得。

Inside this method, we save the important values in the Bundle in the form of key value pairs.

在此方法内部,我们以键值对的形式将重要值保存在Bundle中。

The onSaveInstanceState method looks like :

onSaveInstanceState方法如下所示:

@Overridepublic void onSaveInstanceState(Bundle outState) {super.onSaveInstanceState(outState);}

On the outState bundle instance we add the key value pairs. Following are the methods applicable:

在outState捆绑实例上,我们添加键值对。 以下是适用的方法:

We can pass custom class instances by setting the class as Parcelable or Serializable.

我们可以通过将类设置为Parcelable或Serializable来传递自定义类实例。

Let’s look at an example using Parcelable since it is faster than Serializable.

让我们看一个使用Parcelable的示例,因为它比Serializable更快。

Following is a custom class :

以下是一个自定义类:

public class Model implements Parcelable {public long id;public String name;public Model(long id, String name) {this.id = id;this.name = name;}protected Model(Parcel in) {id = in.readLong();name = in.readString();}public final Creator<Model> CREATOR = new Creator() {@Overridepublic Model createFromParcel(Parcel in) {return new Model(in);}@Overridepublic Model[] newArray(int size) {return new Model[size];}};@Overridepublic int describeContents() {return 0;}@Overridepublic void writeToParcel(Parcel parcel, int i) {parcel.writeLong(id);parcel.writeString(name);}}

writeToParcel method is where we set the class properties on the Parcelable instance.

writeToParcel方法是我们在writeToParcel实例上设置类属性的地方。

Now create an instance of the Model and save it in onSaveInstanceState.

现在创建Model的实例并将其保存在onSaveInstanceState

Model model = new Model(10, "Hello");@Overridepublic void onSaveInstanceState(Bundle outState) {super.onSaveInstanceState(outState);outState.putParcelable("parcelable", model);}

Now we can retrieve these saved values in the onRestoreInstanceState method.

现在,我们可以在onRestoreInstanceState方法中检索这些保存的值。

Note: onSaveInstanceState gets called whenever you press the home button in your application as well.注意 :每当您在应用程序中按下主页按钮时,也会调用onSaveInstanceState。

Another note: Things like EditText can save and restore their content implicitly provided you’ve set an id on the View. Activity will automatically collect View’s State from every single View in the View hierarchy.

另一个注意事项 :只要您在View上设置了id,诸如EditText之类的内容就可以隐式保存和恢复其内容。 活动将从视图层次结构中的每个单个视图自动收集视图状态。

onRestoreInstanceState (onRestoreInstanceState)

This method gets triggered only when something was saved in onSaveInstanceState method.
It gets called after onStart().

仅当在onSaveInstanceState方法中保存了某些内容时,才会触发此方法。
它在onStart()之后被调用。

@Overrideprotected void onRestoreInstanceState(Bundle savedInstanceState) {super.onRestoreInstanceState(savedInstanceState);Model model = savedInstanceState.getParcelable("parcelable");}

Following are the other method available:

以下是可用的其他方法:

The super method implementation restores the view hierarchy.
超级方法实现可还原视图层次结构。

Generally, onRestoreInstanceState isn’t used to restore values often now. The same can be done from the Bundle in the onCreate method. Also since the onCreate method is always called before, it is a good practice to restore the saved instances there only.

通常, onRestoreInstanceState现在不经常用于还原值。 可以通过onCreate方法中的Bundle完成相同的操作。 另外,由于始终在之前调用onCreate方法,因此,仅在此处还原保存的实例是一种好习惯。

In the following section, we’ll be creating a Counter Application in which we’ll save the state of the counter using the above methods.

在下一节中,我们将创建一个计数器应用程序,在其中使用上述方法保存计数器的状态。

项目结构 (Project Structure)

码 (Code)

The code for the activity_main.xml is given below:

下面给出了activity_main.xml的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"xmlns:tools="https://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_margin="16dp"android:orientation="vertical"tools:context=".MainActivity"><EditTextandroid:id="@+id/inName"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="Username" /><EditTextandroid:layout_width="match_parent"android:layout_height="wrap_content"android:hint="Phone number"android:inputType="phone" /><TextViewandroid:id="@+id/textView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="0"android:textSize="32sp" /><Buttonandroid:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="COUNT UP" /></LinearLayout>

In the above layout, the second EditText doesn’t have any id set. So when the device is rotated or any configuration happens that causes the activity to recreate, this EditText contents would be reset.

在上面的布局中,第二个EditText没有设置任何ID。 因此,当设备旋转或发生任何导致活动重新创建的配置时,此EditText内容将被重置。

The code for the MainActivity.java is given below:

MainActivity.java的代码如下:

package com.journaldev.androidsaverestoreinstance;import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;public class MainActivity extends AppCompatActivity {Button button;TextView textView;int counter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);if (savedInstanceState != null) {String message = savedInstanceState.getString("message");Toast.makeText(this, message, Toast.LENGTH_LONG).show();counter = savedInstanceState.getInt("counter", 0);}button = findViewById(R.id.button);textView = findViewById(R.id.textView);textView.setText(String.valueOf(counter));button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {counter = Integer.valueOf(textView.getText().toString()) + 1;textView.setText(String.valueOf(counter));}});}@Overridepublic void onSaveInstanceState(Bundle outState) {super.onSaveInstanceState(outState);outState.putString("message", "This is a saved message");outState.putInt("counter", counter);}@Overrideprotected void onRestoreInstanceState(Bundle savedInstanceState) {super.onRestoreInstanceState(savedInstanceState);Toast.makeText(getApplicationContext(), "onRestoreInstanceState", Toast.LENGTH_SHORT).show();counter = savedInstanceState.getInt("counter", 0);}}

In this the save the integer value of the counter and then when the activity is recreated, the onCreate gets called again. Over there we check if the savedInstanceState Bundle is null or not. If it isn’t we restore the views with the data from the counter.

在这种情况下,保存计数器的整数值,然后在重新创建活动时,再次调用onCreate。 在那儿,我们检查saveInstanceStateState Bundle是否为null。 如果不是,我们将使用计数器中的数据还原视图。

The output of the application in action is given below:

实际应用程序的输出如下:

Notice that the Phone Number field goes empty when the orientation was changed.

请注意,更改方向后,“电话号码”字段为空。

This brings an end to this tutorial. You can download the project from the link below.

本教程到此结束。 您可以从下面的链接下载项目。

AndroidSaveRestoreInstanceAndroidSaveRestoreInstance
Github Project LinkGithub项目链接

翻译自: https://www.journaldev.com/22621/android-onsaveinstancestate-onrestoreinstancestate

Android onSaveInstanceState onRestoreInstanceState相关推荐

  1. Android onSaveInstanceState、onRestoreInstanceState保存数据

    先看例子: @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState ...

  2. 保存现场数据和状态:onSaveInstanceState\onRestoreInstanceState\onCreate()

    当某个activity变得"容易"被系统销毁时,该activity的onSaveInstanceState就会被执行,除非该activity是被用户主动销毁的,例如当用户按BACK ...

  3. Android Activity 生命周期详解及监听

    前言 系列文章: Android Activity 与View 的互动思考 Android Activity 生命周期详解及监听 Android onSaveInstanceState/onResto ...

  4. Android Activity和Intent机制学习笔记

    转自:http://www.cnblogs.com/feisky/archive/2010/01/16/1649081.html Activity Android中,Activity是所有程序的根本, ...

  5. 某android平板项目开发笔记--自定义sharepreference UI

    前言 android对于小数据的存储,提供了一个很好的框架就是Sharepreference,但是,我们在做项目的时候会发现,官方自带的sharepreference 的UI 是远远满足不了我们的需要 ...

  6. [转]Android Activity和Intent机制学习笔记

    Activity Android中,Activity是所有程序的根本,所有程序的流程都运行在Activity之中,Activity具有自己的生命周期(见http://www.cnblogs.com/f ...

  7. android生命周期_Android活动生命周期– 7个阶段和功能

    android生命周期 Activity is one of the primary components of an Android application. In this tutorial, w ...

  8. 【近3万字分享】《Android开发之路——10年老开发精心整理分享》

    目录 前言 1 Android开发学习路线 1.1 大神最新总结(推荐直接看这个) 2021 最新Android知识体系 1.2按内容划分 1.3按阶段划分 1.4Android进阶路线(思维导图) ...

  9. android+面试题

    1.常用的存储方式有哪些?(概率50%) (五种,说出哪五种,五种存储方式什么情况下用.)注意sharepreferes对象支持读取不支持写入,写入引用Editor. SQLite: SQLite是一 ...

最新文章

  1. 一生中用来开会的时间,你知道有多久吗?
  2. 公司-弹出页回调之后加载页面
  3. PaintCode 教程1:动态绘制按钮
  4. jQuery的同胞遍历
  5. 2019年, image captioning论文汇总
  6. C语言快速排序 quick sort 算法(附完整源码)
  7. mysql编译和yum安装哪个好_Centos7下PHP源码编译和通过yum安装的区别和以后的选择...
  8. 3 Sum Closest
  9. 性能分析工具GpProfile
  10. GitHub上最火的40个Android开源项目(一)
  11. sqlserver中获取一张表中列的数据
  12. Cplex安装教程与使用介绍
  13. win11 恢复win10开始菜单及任务栏
  14. 为什么使用Linux
  15. caj转word是怎么进行转换的
  16. 用友公司来访,一些关于用友最新旗舰产品U9的一些介绍(图文)
  17. 家谱二叉树c语言程序,家谱图-二叉树
  18. ARP(地址解析协议)和RARP(逆地址解析协议)
  19. 由于我的BoBo日志需要天气内容,所以在这里留个脚印。
  20. WACV2020:开源基于深度学习方法DeOccNet用来去除透视光场中的前景遮挡

热门文章

  1. c#构造器的一点理解(三)
  2. 批处理mysql命令
  3. [转载] numpy.base_repr 方法解释
  4. verilog之状态机详细解释(一)
  5. redis 基本指令
  6. catch(…) vs catch(CException *)?
  7. 自然语言处理真实项目实战(20170822)
  8. java基础循环 for 、switch 、while 、do while、
  9. 2016 Bird Cup ICPC7th@ahstu--“波导杯”安徽科技学院第七届程序设计大赛
  10. 关于“抵制”易语言的通告