zoukankan      html  css  js  c++  java
  • Android修改默认SharedPreferences文件的路径,SharedPreferences常用工具类

      1 import android.app.Activity;
      2 import android.content.Context;
      3 import android.content.ContextWrapper;
      4 import android.content.SharedPreferences;
      5 
      6 import com.imageviewpager.language.MyApplication;
      7 
      8 import java.io.File;
      9 import java.lang.reflect.Field;
     10 import java.lang.reflect.InvocationTargetException;
     11 import java.lang.reflect.Method;
     12 import java.util.Map;
     13 
     14 public class SPUtil {
     15 
     16     /** debug 环境下允许修改 sp文件的路径 */
     17     public static final boolean isDebug = true;
     18     /** 修改以后的sp文件的路径 MyApplication.getContext().getExternalFilesDir(null).getAbsolutePath()=/sdcard/Android/%package_name%/file */
     19     public static final String FILE_PATH = MyApplication.getContext().getExternalFilesDir(null).getAbsolutePath();
     20 
     21     /**
     22      * 保存数据
     23      *
     24      * @param context
     25      * @param fileName 文件名, 不需要".xml"
     26      * @param keyName
     27      * @param value
     28      */
     29     public static void put(Context context, String fileName, String keyName, Object value) {
     30         SharedPreferences.Editor editor = getSharedPreferences(context, fileName).edit();
     31         if (value instanceof String) {
     32             editor.putString(keyName, (String) value);
     33         } else if (value instanceof Integer) {
     34             editor.putInt(keyName, (Integer) value);
     35         } else if (value instanceof Boolean) {
     36             editor.putBoolean(keyName, (Boolean) value);
     37         } else if (value instanceof Float) {
     38             editor.putFloat(keyName, (Float) value);
     39         } else if (value instanceof Long) {
     40             editor.putLong(keyName, (Long) value);
     41         } else {
     42             editor.putString(keyName, value.toString());
     43         }
     44 
     45         SharedPreferencesCompat.apply(editor);
     46     }
     47 
     48     /**
     49      * 获取数据
     50      *
     51      * @param context
     52      * @param fileName
     53      * @param keyName
     54      * @param defaultValue 默认值
     55      * @return
     56      */
     57     public static Object get(Context context, String fileName, String keyName, Object defaultValue) {
     58         SharedPreferences sp = getSharedPreferences(context, fileName);
     59         if (defaultValue instanceof String) {
     60             return sp.getString(keyName, (String) defaultValue);
     61         } else if (defaultValue instanceof Integer) {
     62             return sp.getInt(keyName, (Integer) defaultValue);
     63         } else if (defaultValue instanceof Boolean) {
     64             return sp.getBoolean(keyName, (Boolean) defaultValue);
     65         } else if (defaultValue instanceof Float) {
     66             return sp.getFloat(keyName, (Float) defaultValue);
     67         } else if (defaultValue instanceof Long) {
     68             return sp.getLong(keyName, (Long) defaultValue);
     69         }
     70         return null;
     71     }
     72 
     73 
     74     /**
     75      * 移除某个key值对应的值
     76      *
     77      * @param context
     78      * @param fileName
     79      * @param keyName
     80      */
     81     public static void remove(Context context, String fileName, String keyName) {
     82         SharedPreferences.Editor editor = getSharedPreferences(context, fileName).edit();
     83         editor.remove(keyName);
     84         SharedPreferencesCompat.apply(editor);
     85     }
     86 
     87     /** 清除所有数据 */
     88     public static void clear(Context context, String fileName) {
     89         SharedPreferences.Editor editor = getSharedPreferences(context, fileName).edit();
     90         editor.clear();
     91         SharedPreferencesCompat.apply(editor);
     92     }
     93 
     94     /**
     95      * 查询某个key是否已经存在
     96      *
     97      * @param context
     98      * @param keyName
     99      * @return
    100      */
    101     public static boolean contains(Context context, String fileName, String keyName) {
    102         return getSharedPreferences(context, fileName).contains(keyName);
    103     }
    104 
    105     /** 返回所有的键值对 */
    106     public static Map<String, ?> getAll(Context context, String fileName) {
    107         return getSharedPreferences(context, fileName).getAll();
    108     }
    109 
    110 
    111     /** 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类 */
    112     private static class SharedPreferencesCompat {
    113         private static final Method sApplyMethod = findApplyMethod();
    114 
    115         /** 反射查找apply的方法 */
    116         @SuppressWarnings({"unchecked", "rawtypes"})
    117         private static Method findApplyMethod() {
    118             try {
    119                 Class clz = SharedPreferences.Editor.class;
    120                 return clz.getMethod("apply");
    121             } catch (NoSuchMethodException e) {
    122             }
    123 
    124             return null;
    125         }
    126 
    127         /** 如果找到则使用apply执行,否则使用commit */
    128         public static void apply(SharedPreferences.Editor editor) {
    129             try {
    130                 if (sApplyMethod != null) {
    131                     sApplyMethod.invoke(editor);
    132                     return;
    133                 }
    134             } catch (IllegalArgumentException e) {
    135             } catch (IllegalAccessException e) {
    136             } catch (InvocationTargetException e) {
    137             }
    138             editor.commit();
    139         }
    140     }
    141 
    142     /**
    143      * @param context
    144      * @param fileName
    145      * @return isDebug = 返回修改路径(路径不存在会自动创建)以后的 SharedPreferences :%FILE_PATH%/%fileName%.xml<br/>
    146      * !isDebug = 返回默认路径下的 SharedPreferences : /data/data/%package_name%/shared_prefs/%fileName%.xml
    147      */
    148     private static SharedPreferences getSharedPreferences(Context context, String fileName) {
    149         if (isDebug) {
    150             try {
    151                 // 获取ContextWrapper对象中的mBase变量。该变量保存了ContextImpl对象
    152                 Field field = ContextWrapper.class.getDeclaredField("mBase");
    153                 field.setAccessible(true);
    154                 // 获取mBase变量
    155                 Object obj = field.get(context);
    156                 // 获取ContextImpl。mPreferencesDir变量,该变量保存了数据文件的保存路径
    157                 field = obj.getClass().getDeclaredField("mPreferencesDir");
    158                 field.setAccessible(true);
    159                 // 创建自定义路径
    160                 File file = new File(FILE_PATH);
    161                 // 修改mPreferencesDir变量的值
    162                 field.set(obj, file);
    163                 // 返回修改路径以后的 SharedPreferences :%FILE_PATH%/%fileName%.xml
    164                 return context.getSharedPreferences(fileName, Activity.MODE_PRIVATE);
    165             } catch (NoSuchFieldException e) {
    166                 e.printStackTrace();
    167             } catch (IllegalArgumentException e) {
    168                 e.printStackTrace();
    169             } catch (IllegalAccessException e) {
    170                 e.printStackTrace();
    171             }
    172         }
    173         // 返回默认路径下的 SharedPreferences : /data/data/%package_name%/shared_prefs/%fileName%.xml
    174         return context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
    175     }
    176 
    177 }

    转自:http://www.cnblogs.com/Westfalen/p/5380737.html

  • 相关阅读:
    directUI
    PyLucene测试成功
    MFC笔记(1)CPaintDC, CClientDC
    sprintf缓冲区溢出
    2.5 攻击示例:对Microsoft C++编译器的攻击 ZZ
    C++笔记(3)类中与类外的运算符重载
    C++笔记(2)public,private,protected关键字
    RTSP协议
    使用虚函数,减少累赘的if/else/switch
    C++笔记(4)成员函数定义在类内与类外
  • 原文地址:https://www.cnblogs.com/Sharley/p/6552546.html
Copyright © 2011-2022 走看看