SharedPreferences 与一类的静态全局变量有何不同? [英] How does SharedPreferences differ from a static global variable of one class?

查看:79
本文介绍了SharedPreferences 与一类的静态全局变量有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经解释了以下关于 SharedPreferences 的内容,并且对它们的功能有点怀疑.这是我发现的:

I have interpreted the following about SharedPreferences and have a bit of doubt of what they are capable of. Here is what I found:

Android SharedPreferences 用于一个全球化的变量,以便我们可以在整个应用程序中使用 SharedPreferences存储和检索数据而不是在一个类中定义静态变量并让该类用于检索整个应用中的变量.

Android SharedPreferences are used for the globalization of a variable so that throughout the application we can use SharedPreferences to store and retrieve data instead of defining static variables in one class and let the class be used to retrieve the variables throughout the app.

谁能解释一下这是否正确.如果我遗漏了主要差异,请告诉我.谢谢.

Can someone explain whether this is correct. If there are major differences that I'm missing please let me know. Thanks.

推荐答案

当保存 sharedpreferences 时,android 系统只是在你的 app 目录中创建一个新的 xml 文件来保存这些值.因此,如果您的应用程序被杀死,这些变量将被保存.并且变量始终可以从任何活动中读取,因为它们存储在文件中.

When saving sharedpreferences, the android system just creates a new xml file in your app directory holding those values. So if your app gets killed those variables will be saved. And the variables are always readable from any activity because they are stored in a file.

当存储共享首选项时,您使用一个键(最终静态字符串)稍后访问它们,也许这个键就是他们谈论静态时的意思

When storing sharedpreferences you use a key (final static String) to access them later, maybe that key is what they mean when talking about static's

小例子:

静态:

public static final String PREFS_NAME = "settings"
public static final String SILENT_MODE = "silentMode";

在您应用的任何活动中:

In any activity of your app:

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean(SILENT_MODE, false);

编辑自:http://developer.android.com/guide/topics/data/data-storage.html#pref

这篇关于SharedPreferences 与一类的静态全局变量有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆