创建SharedPreference的工具类

作者: looper1211 | 来源:发表于2016-06-05 02:14 被阅读1963次

在Android开发中,会有各种各样的工具类帮助我们快速进行项目开发,本次实现对SharedPreference的工具类化

/**
 * 
 * @author Looper
 *
 */
public class SPUtils {

    public static String FILLNAME = "config";

    /**
     * 存入某个key对应的value值
     * 
     * @param context
     * @param key
     * @param value
     */
    public static void put(Context context, String key, Object value) {
        SharedPreferences sp = context.getSharedPreferences(FILLNAME, Context.MODE_PRIVATE);
        Editor edit = sp.edit();
        if (value instanceof String) {
            edit.putString(key, (String) value);
        } else if (value instanceof Integer) {
            edit.putInt(key, (Integer) value);
        } else if (value instanceof Boolean) {
            edit.putBoolean(key, (Boolean) value);
        } else if (value instanceof Float) {
            edit.putFloat(key, (Float) value);
        } else if (value instanceof Long) {
            edit.putLong(key, (Long) value);
        }
        SharedPreferencesCompat.EditorCompat.getInstance().apply(edit);
    }

    /**
     * 得到某个key对应的值
     * 
     * @param context
     * @param key
     * @param defValue
     * @return
     */
    public static Object get(Context context, String key, Object defValue) {
        SharedPreferences sp = context.getSharedPreferences(FILLNAME, Context.MODE_PRIVATE);
        if (defValue instanceof String) {
            return sp.getString(key, (String) defValue);
        } else if (defValue instanceof Integer) {
            return sp.getInt(key, (Integer) defValue);
        } else if (defValue instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defValue);
        } else if (defValue instanceof Float) {
            return sp.getFloat(key, (Float) defValue);
        } else if (defValue instanceof Long) {
            return sp.getLong(key, (Long) defValue);
        }
        return null;
    }

    /**
     * 返回所有数据
     * 
     * @param context
     * @return
     */
    public static Map<String, ?> getAll(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILLNAME, Context.MODE_PRIVATE);
        return sp.getAll();
    }

    /**
     * 移除某个key值已经对应的值
     * 
     * @param context
     * @param key
     */
    public static void remove(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILLNAME, Context.MODE_PRIVATE);
        Editor edit = sp.edit();
        edit.remove(key);
        SharedPreferencesCompat.EditorCompat.getInstance().apply(edit);
    }

    /**
     * 清除所有内容
     * 
     * @param context
     */
    public static void clear(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILLNAME, Context.MODE_PRIVATE);
        Editor edit = sp.edit();
        edit.clear();
        SharedPreferencesCompat.EditorCompat.getInstance().apply(edit);
    }

}

从上面的代码,我们可以看到,凡是需要编辑数据的最后都采用了

SharedPreferencesCompat.EditorCompat.getInstance().apply(edit);

科普一下,起先,Android的Editor只有commit一个提交方法,后来呢,应该是在Google开发Gingerbread的时候,这帮googlers折腾了一堆优化性能的方法,然后就出来一个apply接口

二者有啥区别呢?

  • apply没有返回值而commit返回boolean表明修改是否提交成功
  • apply是将修改数据原子提交到内存,然后异步真正提交到硬件磁盘;而commit是同步的提交到硬件磁盘,因此,在多个并发的提交commit的时候,他们会等待正在处理的commit保存到磁盘后在操作,从而降低了效率。而apply只是原子的提交到内容,后面有调用apply的函数的将会直接覆盖前面的内存数据,这样从一定程度上提高了很多效率。

如果不关注返回值或在程序的main线程使用时,推荐使用apply(),效率比较高!

为啥不直接使用Editor.appley()?
这里涉及了一个api版本问题,Editor的apply()是在API 9以后新增的,所以为了兼容API 9以下的版本,当我们没有aplly()方法的时候,才调用commit()方法。
参见 SharedPreferencesCompat.java 源码

public class SharedPreferencesCompat {

    public static class EditorCompat {

        private static EditorCompat sInstance;

        private interface Helper {
            void apply(@NonNull SharedPreferences.Editor editor);
        }

        private static class EditorHelperBaseImpl implements Helper {

            @Override
            public void apply(@NonNull SharedPreferences.Editor editor) {
                editor.commit();
            }
        }

        private static class EditorHelperApi9Impl implements Helper {

            @Override
            public void apply(@NonNull SharedPreferences.Editor editor) {
                EditorCompatGingerbread.apply(editor);
            }
        }

        private final Helper mHelper;

        private EditorCompat() {
            if (Build.VERSION.SDK_INT >= 9) {
                mHelper = new EditorHelperApi9Impl();
            } else {
                mHelper = new EditorHelperBaseImpl();
            }
        }

        public static EditorCompat getInstance() {
            if (sInstance == null) {
                sInstance = new EditorCompat();
            }
            return sInstance;
        }

        public void apply(@NonNull SharedPreferences.Editor editor) {
            mHelper.apply(editor);
        }
    }

}

相关文章

网友评论

  • 敲代码的鸡:请问一下如果想根据不同的用户创建不同的sp文件是不是可以这样
    SPUtils.FILLNAME =“自定义文件名”;
  • ef3d52f73e1c:老毕,666
  • be7e2ba71f87:Apply接口打错了
    looper1211:@be7e2ba71f87 多谢提醒,已经修改

本文标题:创建SharedPreference的工具类

本文链接:https://www.haomeiwen.com/subject/xstrdttx.html