用于处理默认共享首选项的我有个帮助班。我只检索一次首选项,并包装我所需的所有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
}我有两个问题想完全肯定:
ctx.getApplicationContext()?我对Froyo和up感兴趣
发布于 2013-12-31 02:28:54
使用同步,但我建议使用类似于ReentrantLock (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html)的东西,而不是“同步”。它通常更有表现力。
任何上下文都会工作,当然只要它不是空的。我只需要在这里使用应用程序上下文,这将使调用方不必提供它。公开对它的静态引用,如下所示:静态的方式获得‘上下文’在Android上?
https://stackoverflow.com/questions/20846812
复制相似问题