SharedPreferences的最佳实践

2016-01-26  本文已影响3035人  小武站台

原文:Best practices for SharedPreferences

Android提供了很多种保存应用程序数据的方法。其中一种就是用SharedPreferences对象来保存我们私有的键值(key-value)数据。

所有的逻辑都是基于下面三个类:

SharedPreferences

SharedPreferences是其中最重要的。它负责获取(解析)存储的数据,提供获取Editor对象的接口和添加或移除OnSharedPreferenceChangeListener的接口。

Editor

SharedPreferences.Editor是一个用来修改SharedPreferences对象值的接口。所有在Editor的修改会进行批处理,同时只有你调用了commit()或者apply()的时候才会复制到原来的SharedPreferences。

性能和技巧

示例代码

    public class PreferencesManager {
    
        private static final String PREF_NAME = "com.example.app.PREF_NAME";
        private static final String KEY_VALUE = "com.example.app.KEY_VALUE";
    
        private static PreferencesManager sInstance;
        private final SharedPreferences mPref;
    
        private PreferencesManager(Context context) {
            mPref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        }
    
        public static synchronized void initializeInstance(Context context) {
            if (sInstance == null) {
                sInstance = new PreferencesManager(context);
            }
        }
    
        public static synchronized PreferencesManager getInstance() {
            if (sInstance == null) {
                throw new IllegalStateException(PreferencesManager.class.getSimpleName() +
                        " is not initialized, call initializeInstance(..) method first.");
            }
            return sInstance;
        }
    
        public void setValue(long value) {
            mPref.edit()
                    .putLong(KEY_VALUE, value)
                    .commit();
        }
    
        public long getValue() {
            return mPref.getLong(KEY_VALUE, 0);
        }
    
        public void remove(String key) {
            mPref.edit()
                    .remove(key)
                    .commit();
        }
    
        public boolean clear() {
            return mPref.edit()
                    .clear()
                    .commit();
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读