退出时如何保存 Activity 的状态?安卓
我有一个基本的应用程序,其中包含文本输入、旋转器输入和第二个旋转器输入,其数组取决于“选项”菜单中更改的设置。
目前,当我在应用程序中按 Home 或按 Return 时,我要么返回桌面,要么循环返回最近输入的旧输入。
如何防止我的应用程序打开自身的多个实例,以便在任何给定时间只有一个实例运行,然后如何保存输入到输入中的数据以及在选项菜单中选择的设置?
我对 Java 有点陌生,所以如果这是一个简单的问题,我深表歉意。
I have a basic app with text inputs, a spinner input, and a second spinner input whose array depends on a setting changed in the Options menu.
Currently, when I press Home or press Return while in my app, I either return to the desktop or cycle back through old inputs i put in recently.
How can I prevent my app from opening multiple instances of itself so that there is only one instance running at any given time, and then how can I save the data entered into inputs, and the settings chosen in my option menu?
I'm a bit new to Java, so I apologize if this is a simple problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的活动中覆盖 onSaveInstanceState 和 onRestoreInstanceState。这些方法将允许您将数据保存到 Bundle 您还可以保存数据到首选项。在我的所有应用程序中,我都重写 onSaveInstanceState 和 onRestoreInstanceState 以将值保存和加载到 Bundle。我还将数据保存到 onPause 中的首选项并在 onResume 中加载首选项。另外,在 onCreate(Bundle savingInstanceState) 中,我做了这样的检查
这些做法一直对我有用。
In your acticity override onSaveInstanceState and onRestoreInstanceState. These methods will allow you to save data into a Bundle You can also save data to Preferences. In all of my applications I override both onSaveInstanceState and onRestoreInstanceState to save and load values to a Bundle. I also save data to preferences in onPause and load preferences in onResume. Also in onCreate(Bundle savedInstanceState) I do a check like this
These practices have always worked for me.
您必须在 Activity 上使用
onPause
重写方法并将数据保留在某处(可能是共享首选项)。然后
onResume
您必须从持久性存储中读回它们并填充您的控件。当您想要处理后退或主页按钮按下时,
onSaveInstanceState
和restoreInstanceState
不是您的朋友。You will have to use
onPause
overridden method on your activity and persist your data somewhere (shared preferences probably).Then
onResume
you have to read them back from persistance storage and populate your controls.onSaveInstanceState
andrestoreInstanceState
is not your friend when you want to handle back or home button presses.