在关闭应用程序之前保存值?

Save values before close the app?(在关闭应用程序之前保存值?)

本文介绍了在关闭应用程序之前保存值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在关闭应用程序之前保存一些值.但我不知道是否必须创建一个新文件(.txt)并将其保存;或者我可以更改 strings.xml 文件,当我下次打开应用程序时,保存的值将是正确的保存值,或者是我在第一次使用之前定义它们的 walues.我知道存在从 strings.xml 文件读取的非常简单的方法,因此我认为必须有一种方法可以在关闭之前在此文件中设置值(但我在网上找不到).感谢您提供任何示例或您的建议和解释.

I want to save some values before i closed the app. But i don't know if i must create a new file(.txt) and save it in; or i just can change strings.xml file and when i open app next time the saved values will be the right saved values or will be walues which i define them before first using. I know that exist really easy way to read from strings.xml file and so i think that there must be a way to set values in this file before closing (but i can't find on the net). Thanks for any examples or yours advice and explanation.

推荐答案

Android 提供 SharedPreferences 类来帮助您保存简单的应用程序数据.您可以使用 SharedPreferences 类来保存配置信息或任何您想要的.当您将应用程序置于后台或关闭它时,将调用 onStop().你可以重写它来实现你想要的.

Android provides the SharedPreferences class to help you save simple application data. You can use SharedPreferences class to save the config information or anything you want. When you put the application in background or close it, onStop() will be called. You can override it to implement what you want.

SharedPreferences 类的使用非常简单:

Usage of SharedPreferences class is very simple:

第 1 步:使用 SharedPreferences 对象编写

step 1: Writing with SharedPreferences object

//Create a object SharedPreferences from getSharedPreferences("name_file",MODE_PRIVATE) of Context
private SharedPreferences pref;
pref = getSharedPreferences("info", MODE_PRIVATE);
//Using putXXX - with XXX is type data you want to write like: putString, putInt...   from      Editor object
Editor editor = pref.edit();
editor.putString("key5","value5");
//finally, when you are done saving the values, call the commit() method.   
editor.commit()

第二步:使用 SharedPreferences 对象读取

step2: Reading with SharedPreferences object

//get SharedPreferences from getSharedPreferences("name_file", MODE_PRIVATE)
SharedPreferences shared = getSharedPreferences("info",MODE_PRIVATE)
//Using getXXX- with XX is type date you wrote to file "name_file"
 String string_temp = shared.getString("key5");

MODE_PRIVATE 常量表示共享首选项文件只能由创建它的应用程序打开.

The MODE_PRIVATE constant indicates that the shared preference file can only be opened by the application that created it.

共享首选项文件以 XML 文件的形式保存在 /data/data//shared_prefs 文件夹中

The shared preferences file is save as an XML file in /data/data/<package_name>/shared_prefs folder

这篇关于在关闭应用程序之前保存值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在关闭应用程序之前保存值?

基础教程推荐