目前项目中在轻量级存储上使用的是 SharedPreferences, 虽然 SP 兼容性极好, 但 SP 的低性能一直被诟病, 线上也出现了一些因为 SP 导致的 ANR
网上有很多针对 SP 的优化方案, 这里笔者使用的是通过 Hook SP 在 Application 中的创建, 将其替换成自定义的 SP 的方式来增强性能, 但 SDK 28 以后禁止反射 QueuedWork.getHandler 接口, 这个方式就失效了
因此需要一种替代的轻量级存储方案, MMKV 便是这样的一个框架;
1:下面是我封装了一个mmkv的工具类,可直接copy使用;
代码如下:
package com.pactera.mvpframe.util; import android.os.Parcelable; import com.tencent.mmkv.MMKV; import java.util.Collections; import java.util.Set; /** * @Description: java类作用描述 * @Author: 大魔王老杨 * @Date: 12/29/20 11:18 AM */ public class SpUtils { private static SpUtils mSpUtils; private static MMKV sMMKV; public static SpUtils getInstance() { if (mSpUtils == null) { synchronized (SpUtils.class) { if (mSpUtils == null) { mSpUtils = new SpUtils(); } } } if (sMMKV == null) { sMMKV = MMKV.defaultMMKV(); } return mSpUtils; } /** * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法 * * @param key * @param object */ public void encode(String key, Object object) { if (object instanceof String) { sMMKV.encode(key, (String) object); } else if (object instanceof Integer) { sMMKV.encode(key, (Integer) object); } else if (object instanceof Boolean) { sMMKV.encode(key, (Boolean) object); } else if (object instanceof Float) { sMMKV.encode(key, (Float) object); } else if (object instanceof Long) { sMMKV.encode(key, (Long) object); } else if (object instanceof Double) { sMMKV.encode(key, (Double) object); } else if (object instanceof byte[]) { sMMKV.encode(key, (byte[]) object); } else { sMMKV.encode(key, object.toString()); } } /** * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值 */ public Integer decodeInt(String key) { return sMMKV.decodeInt(key, 0); } public Double decodeDouble(String key) { return sMMKV.decodeDouble(key, 0.00); } public Long decodeLong(String key) { return sMMKV.decodeLong(key, 0L); } public Boolean decodeBoolean(String key) { return sMMKV.decodeBool(key, false); } public Float decodeFloat(String key) { return sMMKV.decodeFloat(key, 0F); } public byte[] decodeBytes(String key) { return sMMKV.decodeBytes(key); } public String decodeString(String key) { return sMMKV.decodeString(key, ""); } public Set<String> decodeStringSet(String key) { return sMMKV.decodeStringSet(key, Collections.<String>emptySet()); } public Parcelable decodeParcelable(String key) { return sMMKV.decodeParcelable(key, null); } /** * 移除某个key对 * * @param key */ public void removeValueForKey(String key) { sMMKV.removeValueForKey(key); } /** * 同时移除多个key对 * * @param strings */ public void removeValuesForKeys(String[] strings) { sMMKV.removeValuesForKeys(strings); } /** * 清除所有key */ public void clearAll() { sMMKV.clearAll(); } }
2:如何使用
(1)存:
SpUtils.getInstance().encode("key","value");
(2)取
SpUtils.getInstance().decodeString("key"));
并且支持同时移除多个key对以及所有key;