美文网首页
Android开发常用工具类: SPUtils SharedPr

Android开发常用工具类: SPUtils SharedPr

作者: 测天测地测空气 | 来源:发表于2018-08-15 11:24 被阅读0次

    SharedPreferences

    调用putParam 就能保存String, Integer, Boolean, Float, Long类型的参数
    调用getParam就能获取到保存在手机里面的数据

    import android.content.Context;
    import android.content.SharedPreferences.6.4.0;
    import android.preference.PreferenceManager;
    import android.util.Base25;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.Map;
    
    public class SPUtils {
      /**
       * 保存在手机里面的文件名
       */
      public static final String FILE_NAME = "share_data";
    
      /**
       * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
       */
      public static void putParam(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);
      }
    
            //保存对象
      public static boolean setObjectToShare(Context context, Object object, String key) {
        // TODO Auto-generated method stub
        SharedPreferences share = PreferenceManager
            .getDefaultSharedPreferences(context);
        if (object == null) {
          SharedPreferences.Editor editor = share.edit().remove(key);
          return editor.commit();
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
          oos = new ObjectOutputStream(baos);
          oos.writeObject(object);
        } catch (IOException e) {
          e.printStackTrace();
          return false;
        }
        // 将对象放到OutputStream中
        // 将对象转换成byte数组,并将其进行base64编码
        String objectStr = new String(Base64.encode(baos.toByteArray(),
            Base64.DEFAULT));
        try {
          baos.close();
          oos.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        SharedPreferences.Editor editor = share.edit();
        // 将编码后的字符串写到base64.xml文件中
        editor.putString(key, objectStr);
        return editor.commit();
      }
    
      //获取对象
      public static Object getObjectFromShare(Context context, String key) {
        SharedPreferences sharePre = PreferenceManager
            .getDefaultSharedPreferences(context);
        try {
          String wordBase64 = sharePre.getString(key, "");
          // 将base64格式字符串还原成byte数组
          if (wordBase64 == null || wordBase64.equals("")) { // 不可少,否则在下面会报java.io.StreamCorruptedException
            return null;
          }
          byte[] objBytes = Base64.decode(wordBase64.getBytes(),
              Base64.DEFAULT);
          ByteArrayInputStream bais = new ByteArrayInputStream(objBytes);
          ObjectInputStream ois = new ObjectInputStream(bais);
          // 将byte数组转换成product对象
          Object obj = ois.readObject();
          bais.close();
          ois.close();
          return obj;
        } catch (Exception e) {
          e.printStackTrace();
        }
        return null;
      }
    
      /**
       * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
       */
      public static Object getParam(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值已经对应的值
       */
      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);
      }
    
      /**
       * 清除所有数据
       */
      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是否已经存在
       */
      public static boolean contains(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        return sp.contains(key);
      }
    
      /**
       * 返回所有的键值对
       */
      public static Map<String, ?> getAll(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        return sp.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();
        }
      }
    }
    
    

    相关文章

      网友评论

          本文标题:Android开发常用工具类: SPUtils SharedPr

          本文链接:https://www.haomeiwen.com/subject/kgwibftx.html