Android 常用工具類之SPUtil,可以修改默認sp文件的路徑


參考:

1.  利用Java反射機制改變SharedPreferences存儲路徑    Singleton1900

2.  Android快速開發系列 10個常用工具類        Hongyang

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;

import com.imageviewpager.language.MyApplication;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public class SPUtil {

    /** debug 環境下允許修改 sp文件的路徑 */
    public static final boolean isDebug = true;
    /** 修改以后的sp文件的路徑 MyApplication.getContext().getExternalFilesDir(null).getAbsolutePath()=/sdcard/Android/%package_name%/file */
    public static final String FILE_PATH = MyApplication.getContext().getExternalFilesDir(null).getAbsolutePath();

    /**
     * 保存數據
     *
     * @param context
     * @param fileName 文件名, 不需要".xml"
     * @param keyName
     * @param value
     */
    public static void put(Context context, String fileName, String keyName, Object value) {
        SharedPreferences.Editor editor = getSharedPreferences(context, fileName).edit();
        if (value instanceof String) {
            editor.putString(keyName, (String) value);
        } else if (value instanceof Integer) {
            editor.putInt(keyName, (Integer) value);
        } else if (value instanceof Boolean) {
            editor.putBoolean(keyName, (Boolean) value);
        } else if (value instanceof Float) {
            editor.putFloat(keyName, (Float) value);
        } else if (value instanceof Long) {
            editor.putLong(keyName, (Long) value);
        } else {
            editor.putString(keyName, value.toString());
        }

        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 獲取數據
     *
     * @param context
     * @param fileName
     * @param keyName
     * @param defaultValue 默認值
     * @return
     */
    public static Object get(Context context, String fileName, String keyName, Object defaultValue) {
        SharedPreferences sp = getSharedPreferences(context, fileName);
        if (defaultValue instanceof String) {
            return sp.getString(keyName, (String) defaultValue);
        } else if (defaultValue instanceof Integer) {
            return sp.getInt(keyName, (Integer) defaultValue);
        } else if (defaultValue instanceof Boolean) {
            return sp.getBoolean(keyName, (Boolean) defaultValue);
        } else if (defaultValue instanceof Float) {
            return sp.getFloat(keyName, (Float) defaultValue);
        } else if (defaultValue instanceof Long) {
            return sp.getLong(keyName, (Long) defaultValue);
        }
        return null;
    }


    /**
     * 移除某個key值對應的值
     *
     * @param context
     * @param fileName
     * @param keyName
     */
    public static void remove(Context context, String fileName, String keyName) {
        SharedPreferences.Editor editor = getSharedPreferences(context, fileName).edit();
        editor.remove(keyName);
        SharedPreferencesCompat.apply(editor);
    }

    /** 清除所有數據 */
    public static void clear(Context context, String fileName) {
        SharedPreferences.Editor editor = getSharedPreferences(context, fileName).edit();
        editor.clear();
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 查詢某個key是否已經存在
     *
     * @param context
     * @param keyName
     * @return
     */
    public static boolean contains(Context context, String fileName, String keyName) {
        return getSharedPreferences(context, fileName).contains(keyName);
    }

    /** 返回所有的鍵值對 */
    public static Map<String, ?> getAll(Context context, String fileName) {
        return getSharedPreferences(context, fileName).getAll();
    }


    /** 創建一個解決SharedPreferencesCompat.apply方法的一個兼容類 */
    private static class SharedPreferencesCompat {
        private static final Method sApplyMethod = findApplyMethod();

        /** 反射查找apply的方法 */
        @SuppressWarnings({"unchecked", "rawtypes"})
        private static Method findApplyMethod() {
            try {
                Class clz = SharedPreferences.Editor.class;
                return clz.getMethod("apply");
            } catch (NoSuchMethodException e) {
            }

            return null;
        }

        /** 如果找到則使用apply執行,否則使用commit */
        public static void apply(SharedPreferences.Editor editor) {
            try {
                if (sApplyMethod != null) {
                    sApplyMethod.invoke(editor);
                    return;
                }
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
            editor.commit();
        }
    }

    /**
     * @param context
     * @param fileName
     * @return isDebug = 返回修改路徑(路徑不存在會自動創建)以后的 SharedPreferences :%FILE_PATH%/%fileName%.xml<br/>
     * !isDebug = 返回默認路徑下的 SharedPreferences : /data/data/%package_name%/shared_prefs/%fileName%.xml
     */
    private static SharedPreferences getSharedPreferences(Context context, String fileName) {
        if (isDebug) {
            try {
                // 獲取ContextWrapper對象中的mBase變量。該變量保存了ContextImpl對象
                Field field = ContextWrapper.class.getDeclaredField("mBase");
                field.setAccessible(true);
                // 獲取mBase變量
                Object obj = field.get(context);
                // 獲取ContextImpl。mPreferencesDir變量,該變量保存了數據文件的保存路徑
                field = obj.getClass().getDeclaredField("mPreferencesDir");
                field.setAccessible(true);
                // 創建自定義路徑
                File file = new File(FILE_PATH);
                // 修改mPreferencesDir變量的值
                field.set(obj, file);
                // 返回修改路徑以后的 SharedPreferences :%FILE_PATH%/%fileName%.xml
                return context.getSharedPreferences(fileName, Activity.MODE_PRIVATE);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        // 返回默認路徑下的 SharedPreferences : /data/data/%package_name%/shared_prefs/%fileName%.xml
        return context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM