我对 SharedPreferences
的使用有技术问题。我知道这个组件应该用于存储应用程序的用户特定首选项(duh)。我目前正在开发一个计时器应用程序,并且需要一些关于计时器状态的持久信息(即暂停,开始时间等等),并且该信息与用户无关或与用户无关。
我认为对这个简单变量使用SQLite存储是一个重载,因为我只有一个表只有一行,并且游标管理应该是异步的,因为不应该在UI线程中查询信息。
是否有更好的数据结构来处理这些持久性变量,或者如果我继续使用首选项可以吗?
信息无法存储在Bundle中,因为如果应用程序停止运行,则不应删除该信息。
答案 0 :(得分:1)
评论已经回答了你的问题,但我会提供一些细节。
共享首选项被序列化并存储在XML中 - 例如,对于com.android.calendar
应用程序,它看起来像这样:
$ adb shell ls -la /data/data/com.android.calendar/shared_prefs/
-rw-rw---- u0_a6 u0_a6 126 2015-08-03 17:21 _has_set_default_values.xml
-rw-rw---- u0_a6 u0_a6 658 2015-08-05 23:05 com.android.calendar_preferences.xml
XML序列化如下:
$ adb shell cat /data/data/com.android.calendar/shared_prefs/com.android.calendar_preferences.xml
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="preferences_week_start_day">2</string>
<string name="preferences_alerts_vibrateWhen">never</string>
<int name="preferred_startView" value="3" />
<boolean name="preferences_alerts" value="true" />
<boolean name="preferences_hide_declined" value="true" />
<string name="preferences_alerts_ringtone">content://settings/system/notification_sound</string>
<boolean name="preferences_home_tz_enabled" value="false" />
<string name="preferences_default_reminder">10</string>
<string name="preferences_home_tz">GMT</string>
<int name="preferences_default_cell_height" value="96" />
</map>
您可以通过查看SharedPreferencesImpl
的来源了解如何做到这一点,XmlUtils.writeMapXml
调用line 636来保存偏好设置......
请参阅Shared Preferences "limit",了解地图中的每个值是如何用XML编写的。
另请参阅此问题XQuery Comparison Expressions,其中@CommonsWare警告整个XML文件被读入内存,因此您不想存储&#34; 100KBS&#34;,我认为他的意思是这样的&#34;数百KB&#34;。合理的任意最大值可能大约几百KB。
所以我说,只要您存储的数据是轻量级的(即合理的读取/存储),就像上面列出的格式的XML一样,你就可以了,不要&# 39;需要Sqlite。