Android 学习笔记之实时保存数据-现场保护

来源:互联网 发布:小白源码论坛 编辑:程序博客网 时间:2024/05/29 07:55
Android 学习笔记之实时保存数据-现场保护onSaveInstanceState()
数据保存:在软件开发中我们希望保存下各个Activity数据,以实现客户数据的时时保存,达到较好的用户体验。
那么我们需要解决如下问题:
1.什么时候保存?
2.保存哪些数据?
    我想保存应用产生的数据,而这些用户的数据是在Activity与用户进行交互的时候产生的,就是界面上的数据,或者状态。
3.如何进行保存?
4.保存到哪里?
5.编写合适的例子?
创造思路,去哪寻找答案,首先,我想保存应用产生的数据,而这些用户的数据是在Activity与用户进行交互的时候产生的,所以我们进入Activity进行查找。
Activity源码:
复制代码
 * <ul> * <li> {@link #onCreate} is where you initialize your activity. Most * importantly, here you will usually call {@link #setContentView(int)} * with a layout resource defining your UI, and using {@link #findViewById} * to retrieve the widgets in that UI that you need to interact with * programmatically.
复制代码

onCreate是初始化你的Activity,在这里你可以调用setContentView(int)与layout资源来定义你的UI界面。使用findViewById来取出您交互的控件

 * <li> {@link #onPause} is where you deal with the user leaving your * activity. Most importantly, any changes made by the user should at this * point be committed (usually to the * {@link android.content.ContentProvider} holding the data). * </ul>

这句的意思是说,onPause是处理用户离开时的方法。最重要的,任何用户操作产生的数据应该在这里进行提交,使用android.content.ContentProvider}来保存数据。

到此我们可以得出结论:
1.什么时候保存?
  一、在onPause时进行保存操作
3.如何进行保存?
使用ContentProvider类进行处理。
怎么处理?继续读
到此,我们要回来看看android.content.ContentProvider
我们进入ContentProvider,但是是用来处理共享数据的,所以我们的结论不是最好的方式。
{@link android.app.Activity#onPause} to commit changes to data and
 * otherwise prepare to stop interacting with the user.
继续向下读,
复制代码
Because of this, you should use the onPause method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate if the activity needs to be re-created. See the Process Lifecycle section for more information on how the lifecycle of a process is tied to the activities it is hosting. Note that it is important to save persistent data in onPause instead of onSaveInstanceState because the later is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.
复制代码

我们可以使用onSaveInstanceState(Bundle)方法进行存储,然后onRestoreInstanceState 处进行处理,即拿到值。

如何使用onSaveInstanceState(Bundle)方法?
我们在layout中加一个文本框和button
0 0