【发布时间】:2014-01-17 18:25:49
【问题描述】:
I have a helper class 用于处理默认的共享首选项。我检索了一次首选项,然后包装了我需要的所有 SP 方法,提供了相同的缓存实例。它是这样的:
public final class AccessPreferences {
private static SharedPreferences prefs; // cache
private static SharedPreferences getPrefs(Context ctx) {
// synchronized is really needed or volatile is all I need (visibility)
SharedPreferences result = prefs;
if (result == null)
synchronized (AccessPreferences.class) {
result = prefs;
if (result == null) {
result = prefs = PreferenceManager
.getDefaultSharedPreferences(ctx);
}
}
return result;
}
public static boolean contains(Context ctx, String key) {
if (key == null)
throw new NullPointerException("Null keys are not permitted");
return getPrefs(ctx).contains(key);
}
//etc
}
我有两个问题想绝对确定:
- 我需要像我一样进行同步还是一个简单的 volatile 就足够了?当然,这个帮助类由不同的线程(UI、Intent 服务等)访问。
- 检索共享首选项时是否需要致电
ctx.getApplicationContext()?
我对 Froyo 及以上感兴趣
【问题讨论】:
标签: android multithreading sharedpreferences android-context