1-SII--SharedPreferences完美封装

简介: 零、前言以前我的SharedPreferences封装类根据不同类型getXXX,setXXX分好多情况。现在回过头看看,咱也是玩过泛型的。突然灵光一闪,"少年,看你骨骼惊奇,泛型了解一下吗。

零、前言

以前我的SharedPreferences封装类根据不同类型getXXX,setXXX分好多情况。现在回过头看看,咱也是玩过泛型的。
突然灵光一闪,"少年,看你骨骼惊奇,泛型了解一下吗。"便有此文。

一、使用

1.写入不同类型:根据泛型
SpUtils<Boolean> spBoolean = new SpUtils<>(this);
spBoolean.put("Boolean", true);
SpUtils<Integer> spInteger = new SpUtils<>(this);
spInteger.put("Integer", 100);
SpUtils<Long> spLong = new SpUtils<>(this);
spLong.put("Long", new Date().getTime());
SpUtils<String> spString = new SpUtils<>(this);
spString.put("String", "I am toly");
SpUtils<Float> spFloat = new SpUtils<>(this);
spFloat.put("Float", 3.14f);
2.读取已设置的值:第二参数是key不存在时,value的默认值
 Boolean reslute = spBoolean.get("Boolean", false);
sp.png

附录一、封装类

/**
 * 作者:张风捷特烈<br/>
 * 时间:2018/2/20:17:57<br/>
 * 邮箱:1981462002@qq.com<br/>
 * 说明:SharedPreferences工具类 :默认apply方式提交<br/>
 */
public class SpUtils<T> {
    /**
     * 上下文
     */
    private Context mContext;

    /**
     * 是否以apply方式提交:否则是commit方式提交
     */
    private boolean isApply = true;

    /**
     * SharedPreferences对象
     */
    private static SharedPreferences sp;

    /**
     * 构造函数 传入上下文
     *
     * @param context 上下文
     */
    public SpUtils(Context context) {
        mContext = context;
    }


    /**
     * 写入至sp中
     *
     * @param key   存储节点名称
     * @param value 存储节点的值 boolean
     * @return 是否插入成功 apply 方式返回null
     */
    public Boolean put(String key, T value) {
        //(存储节点文件名称,读写方式)
        if (sp == null) {
            sp = mContext.getSharedPreferences("config", Context.MODE_PRIVATE);
        }

        SharedPreferences.Editor editor = null;
        if (value instanceof Boolean) {
            editor = sp.edit().putBoolean(key, (Boolean) value);
        }

        if (value instanceof String) {
            editor = sp.edit().putString(key, (String) value);
        }

        if (value instanceof Integer) {
            editor = sp.edit().putInt(key, (Integer) value);
        }

        if (value instanceof Long) {
            editor = sp.edit().putLong(key, (Long) value);
        }
        if (value instanceof Float) {
            editor = sp.edit().putFloat(key, (Float) value);
        }

        if (editor != null) {
            if (isApply) {
                editor.apply();
                return null;
            } else {
                return editor.commit();
            }
        }
        return false;
    }


    /**
     * 从sp中读取
     *
     * @param key      存储节点名称
     * @param defValue 默认值
     * @return 读取boolean标示从sp中
     */
    public T get(String key, T defValue) {
        //(存储节点文件名称,读写方式)
        Object o = new Object();
        if (sp == null) {
            sp = mContext.getSharedPreferences("config", Context.MODE_PRIVATE);
        }

        if (defValue instanceof Boolean) {
            o = (sp.getBoolean(key, (Boolean) defValue));
        }

        if (defValue instanceof String) {
            o = sp.getString(key, (String) defValue);
        }

        if (defValue instanceof Integer) {
            o = sp.getInt(key, (Integer) defValue);
        }

        if (defValue instanceof Long) {
            o = sp.getLong(key, (Long) defValue);
        }
        if (defValue instanceof Float) {
            o = sp.getFloat(key, (Float) defValue);
        }
        return (T) o;
    }

    /**
     * 从sp中移除指定节点
     *
     * @param key 需要移除节点的名称
     * @return 是否插入成功 apply 方式返回null
     */
    public Boolean remove(String key) {
        if (sp == null) {
            sp = mContext.getSharedPreferences("config", Context.MODE_PRIVATE);
        }

        SharedPreferences.Editor editor = sp.edit().remove(key);
        if (isApply) {
            editor.apply();
            return null;
        } else {
            return editor.commit();
        }
    }
    
    /**
     * 设置是否以 apply方式提交
     * @param apply 以apply方式提交,否则:commit
     */
    public void setApply(boolean apply) {
        isApply = apply;
    }

}

附录2:apply和commit

相同点:
1.提交preference修改数据
2.是原子过程

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

综合上述,由于在一个进程中,sharedPreference是单实例,一般不会出现并发冲突,
如果对提交的结果不关心的话,建议使用apply,当然需要确保提交成功且有后续操作的话,还是需要用commit的。

后记、

1.声明:

[1]本文由张风捷特烈原创,转载请注明
[2]欢迎广大编程爱好者共同交流
[3]个人能力有限,如有不正之处欢迎大家批评指证,必定虚心改正
[4]你的喜欢与支持将是我最大的动力

2.连接传送门:

更多安卓技术欢迎访问:安卓技术栈
我的github地址:欢迎star
简书首发,腾讯云+社区同步更新
张风捷特烈个人网站,编程笔记请访问:http://www.toly1994.com

3.联系我

QQ:1981462002
邮箱:1981462002@qq.com
微信:zdl1994328

4.欢迎关注我的微信公众号,最新精彩文章,及时送达:
公众号.jpg
相关文章
|
8月前
|
Java Android开发
Android 中通过Intent传递类对象,通过实现Serializable和Parcelable接口两种方式传递对象
Android 中通过Intent传递类对象,通过实现Serializable和Parcelable接口两种方式传递对象
76 1
|
10月前
|
Android开发
Android的配置文件操作封装,摒弃SharedPreference操作配置漫天乱飞
Android的配置文件操作封装,摒弃SharedPreference操作配置漫天乱飞
|
10月前
|
存储 XML JSON
Android操作配置文件封装类,使用json序列化的方式实现
Android操作配置文件封装类,使用json序列化的方式实现
|
12月前
|
缓存 Java Android开发
Android C++ 系列:JNI 调用时缓存字段和方法 ID
通常我们通过 FindClass 、GetFieldID、GetMethodID 去找到对应的信息也是耗时操作,如果方法被频繁调用(特别是像音视频处理时循环的调用JNI方法传递音视频数据),每次都去查找对应的类和方法ID会很耗性能,所以我们必须将它们缓存起来,达到只创建一次,后面直接使用缓存内容的效果。
90 0
|
12月前
|
XML 存储 缓存
SharedPreferences封装
SharedPreferences封装 存 取 封装类
222 0
|
Java Android开发
Android中Message对象复用原理
Android开发中,我们经常使用Message对象,却很少去探求其复用池的实现原理,是时候揭开它的神秘面纱了!
2622 0
|
存储 XML 数据格式
SharedPreferences源码解析
终于建了一个自己个人小站:https://huangtianyu.gitee.io,以后优先更新小站博客,欢迎进站,O(∩_∩)O~~ 1.简介 写这篇博客目的在于巩固自己对SharedPreferences的理解。
1171 0