我的android应用程序有两种首选项:
1)我在res/xml/preferences.xml中定义了用户首选项,以便用户可以使用PreferenceActivity管理他们的首选项.
2)我想为我的应用程序的全局配置首选项定义另一个文件.
管理我的应用配置偏好的最佳方法是什么?我应该使用配置值创建另一个XML文件,还是应该在strings.xml中指定这些配置值?管理配置首选项的最佳做法是什么?
我想序列化一个自定义Java对象,所以我可以SharedPreferences用来存储它并在另一个Activity中检索它.我不需要持久存储,SharedPreferences我在应用程序关闭时擦除它们.我目前正在使用GSON,但它似乎不适用于Android的SparseArray类型.
我的对象:
public class PartProfile {
private int gameId;
// Some more primitives
private SparseArray<Part> installedParts = new SparseArray<Part>();
// ...
}
public class Part {
private String partName;
// More primitives
}
Run Code Online (Sandbox Code Playgroud)
连载:
Type genericType = new TypeToken<PartProfile>() {}.getType();
String serializedProfile = Helpers.serializeWithJSON(installedParts, genericType);
preferences.edit().putString("Parts", serializedProfile).commit();
Run Code Online (Sandbox Code Playgroud)
serializeWithJSON():
public static String serializeWithJSON(Object o, Type genericType) {
Gson gson = new Gson();
return gson.toJson(o, genericType);
}
Run Code Online (Sandbox Code Playgroud)
反序列化:
Type genericType = new TypeToken<PartProfile>() {}.getType();
PartProfile parts = gson.fromJson(preferences.getString("Parts", …Run Code Online (Sandbox Code Playgroud) 我正在开发基于GCM的应用程序,用户可以在其中订阅多个主题.
我需要知道用户在两个地方订阅了哪些主题:
Subscribe或Unsubscribe按钮GcmPubSub.基本上,如果监听器收到的主题消息不在应用程序的主题列表中,那么我们可能在GCM服务器上有一个"过时的"订阅,并且必须取消订阅.所以基本上我有一个活动和服务,它们都可以访问一些常见的数据,并且都可以修改这些数据.
我已经读过,在活动和服务之间共享数据的一个选项是使用共享首选项:
这适合我的情况,因为我非常满足于分享Set<String>哪些SharedPreferences支持.用户可能只对几个主题感兴趣(例如,最多10个).
这是我的代码,用于检查用户是否订阅了主题:
SharedPreferences preferences = getPreferences(Context.MODE_PRIVATE);
Set<String> subscribedTopics = preferences.getStringSet(AufzugswaechterPreferences.SUBSCRIBED_TOPICS, Collections.<String>emptySet());
boolean subscribedForTopic = subscribedTopics.contains(topic);
Run Code Online (Sandbox Code Playgroud)
这是修改订阅的代码(例如取消订阅):
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getContext());
Set<String> topics = new TreeSet<String>(preferences.getStringSet(AufzugswaechterPreferences.SUBSCRIBED_TOPICS, Collections.<String>emptySet()));
topics.remove(topic);
preferences.edit().putStringSet(AufzugswaechterPreferences.SUBSCRIBED_TOPICS, topics).apply();
Run Code Online (Sandbox Code Playgroud)
但现在我怀疑,如果这是一个合适的方式.我将基本上访问每个检查(在UI或收到的消息中)以及修改的共享首选项.
这是正确的方法吗?我应该直接通过首选项在活动和服务之间共享数据,还是应该以某种方式缓存值?