SharedPreference的封装

来源:互联网 发布:自制题库软件 编辑:程序博客网 时间:2024/06/06 06:32

转载请标明出处:http://blog.csdn.net/changsimeng/article/details/53994654,本文出自:【changsimeng的博客】

对SharedPreference的使用做了建议的封装,对外公布出put,get,remove,clear等等方法;

注意一点,里面所有的commit操作使用了SharedPreferencesCompat.apply进行了替代,目的是尽可能的使用apply代替commit

首先说下为什么,因为commit方法是同步的,并且我们很多时候的commit操作都是UI线程中,毕竟是IO操作,尽可能异步;

所以我们使用apply进行替代,apply异步的进行写入;

但是apply相当于commit来说是new API呢,为了更好的兼容,我们做了适配;

SharedPreferencesCompat也可以给大家创建兼容类提供了一定的参考~~
[java] view plain copy
print?
  1.  import java.lang.reflect.InvocationTargetException;    
  2. import java.lang.reflect.Method;    
  3. import java.util.Map;    
  4.     
  5. import android.content.Context;    
  6. import android.content.SharedPreferences;    
  7.     
  8. public class SPUtils    
  9. {    
  10.     /**  
  11.      * 保存在手机里面的文件名  
  12.      */    
  13.     public static final String FILE_NAME = “share_data”;    
  14.     
  15.     /**  
  16.      * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法  
  17.      *   
  18.      * @param context  
  19.      * @param key  
  20.      * @param object  
  21.      */    
  22.     public static void put(Context context, String key, Object object)    
  23.     {    
  24.     
  25.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,    
  26.                 Context.MODE_PRIVATE);    
  27.         SharedPreferences.Editor editor = sp.edit();    
  28.     
  29.         if (object instanceof String)    
  30.         {    
  31.             editor.putString(key, (String) object);    
  32.         } else if (object instanceof Integer)    
  33.         {    
  34.             editor.putInt(key, (Integer) object);    
  35.         } else if (object instanceof Boolean)    
  36.         {    
  37.             editor.putBoolean(key, (Boolean) object);    
  38.         } else if (object instanceof Float)    
  39.         {    
  40.             editor.putFloat(key, (Float) object);    
  41.         } else if (object instanceof Long)    
  42.         {    
  43.             editor.putLong(key, (Long) object);    
  44.         } else    
  45.         {    
  46.             editor.putString(key, object.toString());    
  47.         }    
  48.     
  49.         SharedPreferencesCompat.apply(editor);    
  50.     }    
  51.     
  52.     /**  
  53.      * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值  
  54.      *   
  55.      * @param context  
  56.      * @param key  
  57.      * @param defaultObject  
  58.      * @return  
  59.      */    
  60.     public static Object get(Context context, String key, Object defaultObject)    
  61.     {    
  62.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,    
  63.                 Context.MODE_PRIVATE);    
  64.     
  65.         if (defaultObject instanceof String)    
  66.         {    
  67.             return sp.getString(key, (String) defaultObject);    
  68.         } else if (defaultObject instanceof Integer)    
  69.         {    
  70.             return sp.getInt(key, (Integer) defaultObject);    
  71.         } else if (defaultObject instanceof Boolean)    
  72.         {    
  73.             return sp.getBoolean(key, (Boolean) defaultObject);    
  74.         } else if (defaultObject instanceof Float)    
  75.         {    
  76.             return sp.getFloat(key, (Float) defaultObject);    
  77.         } else if (defaultObject instanceof Long)    
  78.         {    
  79.             return sp.getLong(key, (Long) defaultObject);    
  80.         }    
  81.     
  82.         return null;    
  83.     }    
  84.     
  85.     /**  
  86.      * 移除某个key值已经对应的值  
  87.      * @param context  
  88.      * @param key  
  89.      */    
  90.     public static void remove(Context context, String key)    
  91.     {    
  92.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,    
  93.                 Context.MODE_PRIVATE);    
  94.         SharedPreferences.Editor editor = sp.edit();    
  95.         editor.remove(key);    
  96.         SharedPreferencesCompat.apply(editor);    
  97.     }    
  98.     
  99.     /**  
  100.      * 清除所有数据  
  101.      * @param context  
  102.      */    
  103.     public static void clear(Context context)    
  104.     {    
  105.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,    
  106.                 Context.MODE_PRIVATE);    
  107.         SharedPreferences.Editor editor = sp.edit();    
  108.         editor.clear();    
  109.         SharedPreferencesCompat.apply(editor);    
  110.     }    
  111.     
  112.     /**  
  113.      * 查询某个key是否已经存在  
  114.      * @param context  
  115.      * @param key  
  116.      * @return  
  117.      */    
  118.     public static boolean contains(Context context, String key)    
  119.     {    
  120.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,    
  121.                 Context.MODE_PRIVATE);    
  122.         return sp.contains(key);    
  123.     }    
  124.     
  125.     /**  
  126.      * 返回所有的键值对  
  127.      *   
  128.      * @param context  
  129.      * @return  
  130.      */    
  131.     public static Map<String, ?> getAll(Context context)    
  132.     {    
  133.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,    
  134.                 Context.MODE_PRIVATE);    
  135.         return sp.getAll();    
  136.     }    
  137.     
  138.     /**  
  139.      * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类  
  140.      *   
  141.      * @author zhy  
  142.      *   
  143.      */    
  144.     private static class SharedPreferencesCompat    
  145.     {    
  146.         private static final Method sApplyMethod = findApplyMethod();    
  147.     
  148.         /**  
  149.          * 反射查找apply的方法  
  150.          *   
  151.          * @return  
  152.          */    
  153.         @SuppressWarnings({ “unchecked”“rawtypes” })    
  154.         private static Method findApplyMethod()    
  155.         {    
  156.             try    
  157.             {    
  158.                 Class clz = SharedPreferences.Editor.class;    
  159.                 return clz.getMethod(“apply”);    
  160.             } catch (NoSuchMethodException e)    
  161.             {    
  162.             }    
  163.     
  164.             return null;    
  165.         }    
  166.     
  167.         /**  
  168.          * 如果找到则使用apply执行,否则使用commit  
  169.          *   
  170.          * @param editor  
  171.          */    
  172.         public static void apply(SharedPreferences.Editor editor)    
  173.         {    
  174.             try    
  175.             {    
  176.                 if (sApplyMethod != null)    
  177.                 {    
  178.                     sApplyMethod.invoke(editor);    
  179.                     return;    
  180.                 }    
  181.             } catch (IllegalArgumentException e)    
  182.             {    
  183.             } catch (IllegalAccessException e)    
  184.             {    
  185.             } catch (InvocationTargetException e)    
  186.             {    
  187.             }    
  188.             editor.commit();    
  189.         }    
  190.     }    
  191.     
  192. }    
 import java.lang.reflect.InvocationTargetException;  import java.lang.reflect.Method;  import java.util.Map;  import android.content.Context;  import android.content.SharedPreferences;  public class SPUtils  {      /**      * 保存在手机里面的文件名      */      public static final String FILE_NAME = "share_data";      /**      * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法      *       * @param context      * @param key      * @param object      */      public static void put(Context context, String key, Object object)      {          SharedPreferences sp = context.getSharedPreferences(FILE_NAME,                  Context.MODE_PRIVATE);          SharedPreferences.Editor editor = sp.edit();          if (object instanceof String)          {              editor.putString(key, (String) object);          } else if (object instanceof Integer)          {              editor.putInt(key, (Integer) object);          } else if (object instanceof Boolean)          {              editor.putBoolean(key, (Boolean) object);          } else if (object instanceof Float)          {              editor.putFloat(key, (Float) object);          } else if (object instanceof Long)          {              editor.putLong(key, (Long) object);          } else          {              editor.putString(key, object.toString());          }          SharedPreferencesCompat.apply(editor);      }      /**      * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值      *       * @param context      * @param key      * @param defaultObject      * @return      */      public static Object get(Context context, String key, Object defaultObject)      {          SharedPreferences sp = context.getSharedPreferences(FILE_NAME,                  Context.MODE_PRIVATE);          if (defaultObject instanceof String)          {              return sp.getString(key, (String) defaultObject);          } else if (defaultObject instanceof Integer)          {              return sp.getInt(key, (Integer) defaultObject);          } else if (defaultObject instanceof Boolean)          {              return sp.getBoolean(key, (Boolean) defaultObject);          } else if (defaultObject instanceof Float)          {              return sp.getFloat(key, (Float) defaultObject);          } else if (defaultObject instanceof Long)          {              return sp.getLong(key, (Long) defaultObject);          }          return null;      }      /**      * 移除某个key值已经对应的值      * @param context      * @param key      */      public static void remove(Context context, String key)      {          SharedPreferences sp = context.getSharedPreferences(FILE_NAME,                  Context.MODE_PRIVATE);          SharedPreferences.Editor editor = sp.edit();          editor.remove(key);          SharedPreferencesCompat.apply(editor);      }      /**      * 清除所有数据      * @param context      */      public static void clear(Context context)      {          SharedPreferences sp = context.getSharedPreferences(FILE_NAME,                  Context.MODE_PRIVATE);          SharedPreferences.Editor editor = sp.edit();          editor.clear();          SharedPreferencesCompat.apply(editor);      }      /**      * 查询某个key是否已经存在      * @param context      * @param key      * @return      */      public static boolean contains(Context context, String key)      {          SharedPreferences sp = context.getSharedPreferences(FILE_NAME,                  Context.MODE_PRIVATE);          return sp.contains(key);      }      /**      * 返回所有的键值对      *       * @param context      * @return      */      public static Map<String, ?> getAll(Context context)      {          SharedPreferences sp = context.getSharedPreferences(FILE_NAME,                  Context.MODE_PRIVATE);          return sp.getAll();      }      /**      * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类      *       * @author zhy      *       */      private static class SharedPreferencesCompat      {          private static final Method sApplyMethod = findApplyMethod();          /**          * 反射查找apply的方法          *           * @return          */          @SuppressWarnings({ "unchecked", "rawtypes" })          private static Method findApplyMethod()          {              try              {                  Class clz = SharedPreferences.Editor.class;                  return clz.getMethod("apply");              } catch (NoSuchMethodException e)              {              }              return null;          }          /**          * 如果找到则使用apply执行,否则使用commit          *           * @param editor          */          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();          }      }  }  

0 0