getDefaultShared preferences(上下文) - 任何上下文? [英] getDefaultSharedPreferences(Context) - any context?

查看:512
本文介绍了getDefaultShared preferences(上下文) - 任何上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<一个href=\"https://github.com/Utumno/AndroidHelpers/blob/master/src/gr/uoa/di/android/helpers/Access$p$pferences.java\"相对=nofollow>我处理的默认一个辅助类共享preferences。我检索preferences曾经和我包所有的SP方法,我需要,提供相同的缓存实例。它是这样:

I have a helper class for dealing with the default shared preferences. I retrieve the preferences once and I wrap all the SP methods I need, providing the same cached instance. It goes like:

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
}

我有两个问题我想是绝对肯定:

I have two questions I want to be absolutely sure about:


  • 请我需要同步的,因为我做的或者简单的挥发性就足够了?当然,这个辅助类是由不同的线程(UI,意图服务等)的访问。

  • 请我需要调用 ctx.getApplicationContext()或不获取共享preferences什么时候?

  • Do I need synchronization as I do or a simple volatile would suffice ? Of course this helper class is accessed by different threads (the UI, Intent services etc).
  • Do I need to call ctx.getApplicationContext() or not when retrieving the shared preferences ?

我感兴趣的升级Froyo和高达

I am interested in Froyo and up

推荐答案

使用同步,但我会建议使用像一个ReentrantLock的(东西的http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html)而不是同步,它通常更高性能的。

Use synchronization, but I would suggest using something like a ReentrantLock (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html) instead of "synchronized". It is generally more performant.

任何情况下都可以工作,只要它不为空,当然。我只想用应用程序上下文在这里,这将节省您的来电者不必为它供给。公开一个静态引用,因为在这里看到:静态的方式来获得在Android上下文?

Any context will work, so long as it's not null of course. I would just use the application context here, which will save your callers from having to supply it. Expose a static reference to it, as seen here: Static Way to get Context on android?

这篇关于getDefaultShared preferences(上下文) - 任何上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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