SharePreference雙重存儲工具

在這裏插入圖片描述

public class MPreferencesUtils {

    private static SharedPreferences sp;
    private static SharedPreferences.Editor editor;
    private static SharedPreferences op;
    private static SharedPreferences.Editor oditor;

    public static void init(Context context) {
        sp = PreferenceManager.getDefaultSharedPreferences(context);
        editor = sp.edit();

        File directory = Environment.getExternalStorageDirectory();
        File dir = new File(directory, "xxx應用名稱/Preferences");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        op = getMySharedPreferences(context, dir, AppUtil.getAppName(context));
        if (op != null) {
            oditor = op.edit();
        }
    }

    private static SharedPreferences getMySharedPreferences(Context context,File dir,String fileName) {
        SharedPreferences sharedPreferences = null;
        try {
            // 獲取 ContextWrapper對象中的mBase變量。該變量保存了 ContextImpl 對象
            Field field_mBase = ContextWrapper.class.getDeclaredField("mBase");
            field_mBase.setAccessible(true);
            // 獲取 mBase變量
            Object obj_mBase = field_mBase.get(context);
            // 獲取 ContextImpl。mPreferencesDir變量,該變量保存了數據文件的保存路徑
            Field field_mPreferencesDir = obj_mBase.getClass().getDeclaredField("mPreferencesDir");
            field_mPreferencesDir.setAccessible(true);
            File souDir = (File) field_mPreferencesDir.get(obj_mBase);
            // 修改mPreferencesDir變量的值
            field_mPreferencesDir.set(obj_mBase, dir);
            // 返回修改路徑以後的 SharedPreferences :%FILE_PATH%/%fileName%.xml
            sharedPreferences= context.getSharedPreferences(fileName,Activity.MODE_PRIVATE);
            // 修改回原來mPreferencesDir變量的值
            field_mPreferencesDir.set(obj_mBase, souDir);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sharedPreferences;
    }

    public static void put(String key, Parcelable parcelable){
        Parcel parcel = Parcel.obtain();
        parcelable.writeToParcel(parcel, 0);
        parcel.setDataPosition(0);
        String value = Base64.encodeToString(parcel.marshall(), Base64.DEFAULT);
        put(key, value);
    }


    public static <T extends Parcelable> T get(String key, Parcelable.Creator<T> creator) {
        String value = get(key, "");
        if (TextUtils.isEmpty(value)) {
            return null;
        }
        Parcel parcel = Parcel.obtain();
        byte[] decode = Base64.decode(value, Base64.DEFAULT);
        parcel.unmarshall(decode, 0, decode.length);
        parcel.setDataPosition(0);//這句話非常重要
        return creator.createFromParcel(parcel);
    }

    public static void put(String key, Serializable object) {
        if (TextUtils.isEmpty(key)) {
            throw new IllegalArgumentException("key is empty");
        }
        if (object == null){
            if (sp.contains(key)){
                editor.remove(key);
                if (op != null) {
                    oditor.remove(key);
                }
            }
            return;
        }
        if (object instanceof String) {
            editor.putString(key, (String) object);
            if (op != null) {
                oditor.putString(key, (String) object);
            }
        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);
            if (op != null) {
                oditor.putInt(key, (Integer) object);
            }
        } else if (object instanceof Boolean) {
            editor.putBoolean(key, (Boolean) object);
            if (op != null) {
                oditor.putBoolean(key, (Boolean) object);
            }
        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
            if (op != null) {
                oditor.putFloat(key, (Float) object);
            }
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
            if (op != null) {
                oditor.putLong(key, (Long) object);
            }
        } else {
            ByteArrayOutputStream outputStream;
            ObjectOutputStream objectOutputStream = null;
            String value = "";
            try {
                outputStream = new ByteArrayOutputStream();
                objectOutputStream = new ObjectOutputStream(outputStream);
                objectOutputStream.writeObject(object);
                value = Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                editor.putString(key, value);
                if (op != null) {
                    oditor.putString(key, value);
                }
                if (objectOutputStream != null) {
                    try {
                        objectOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        editor.apply();
        if (op != null) {
            oditor.apply();
        }
    }


    public static <T extends Serializable> T get(String key, T defaut) {
        if (TextUtils.isEmpty(key)) {
            return defaut;
        }
        T value = defaut;
        if (defaut instanceof String) {
            value = (T) sp.getString(key, (String) defaut);
            if (value == defaut && op != null) {
                value = (T) op.getString(key, (String) defaut);
                if (value != defaut) {
                    editor.putString(key, (String) value);
                    editor.apply();
                }
            }
        } else if (defaut instanceof Integer) {
            value = (T) new Integer(sp.getInt(key, (Integer) defaut));
            if (value == defaut && op != null) {
                value = (T) new Integer(op.getInt(key, (Integer) defaut));
                if (value != defaut) {
                    editor.putInt(key, (Integer) value);
                    editor.apply();
                }
            }
        } else if (defaut instanceof Boolean) {
            value = (T) new Boolean(sp.getBoolean(key, (Boolean) defaut));
            if (value == defaut && op != null) {
                value = (T) new Boolean(op.getBoolean(key, (Boolean) defaut));
                if (value != defaut) {
                    editor.putBoolean(key, (Boolean) value);
                    editor.apply();
                }
            }
        } else if (defaut instanceof Float) {
            value = (T) new Float(sp.getFloat(key, (Float) defaut));
            if (value == defaut && op != null) {
                value = (T) new Float(op.getFloat(key, (Float) defaut));
                if (value != defaut) {
                    editor.putFloat(key, (Float) value);
                    editor.apply();
                }
            }
        } else if (defaut instanceof Long) {
            value = (T) new Long(sp.getLong(key, (Long) defaut));
            if (value == defaut && op != null) {
                value = (T) new Long(op.getLong(key, (Long) defaut));
                if (value != defaut) {
                    editor.putLong(key, (Long) value);
                    editor.apply();
                }
            }
        } else {
            String str = sp.getString(key, "");
            if (TextUtils.isEmpty(str) && op != null) {
                str = op.getString(key, "");
                if (TextUtils.isEmpty(str)) {
                    return defaut;
                }
                editor.putString(key, (String) str);
                editor.apply();
            }
            ByteArrayInputStream inputStream;
            ObjectInputStream objectInputStream = null;
            try {
                inputStream = new ByteArrayInputStream(Base64.decode(str, Base64.DEFAULT));
                objectInputStream = new ObjectInputStream(inputStream);
                value = (T) objectInputStream.readObject();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (objectInputStream != null) {
                    try {
                        objectInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return value;
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章