SPUtils.java 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package me.yoqi.android.utils;
  2. import android.content.Context;
  3. import android.content.SharedPreferences;
  4. import android.content.SharedPreferences.Editor;
  5. import java.util.Map;
  6. import java.util.Set;
  7. public class SPUtils {
  8. private static final String SP_NAME = "common";
  9. private static SPUtils mSpUtils;
  10. private SharedPreferences sp;
  11. private Editor editor;
  12. public SPUtils(Context mContext) {
  13. sp = mContext.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
  14. editor = sp.edit();
  15. }
  16. public static SPUtils getInstance(Context context) {
  17. if (mSpUtils == null) {
  18. synchronized (SPUtils.class) {
  19. if (mSpUtils == null) {
  20. mSpUtils = new SPUtils(context);
  21. return mSpUtils;
  22. }
  23. }
  24. }
  25. return mSpUtils;
  26. }
  27. public void putBoolean(String key, Boolean value) {
  28. editor.putBoolean(key, value);
  29. editor.commit();
  30. }
  31. public boolean getBoolean(String key, Boolean defValue) {
  32. return sp.getBoolean(key, defValue);
  33. }
  34. public void putString(String key, String value) {
  35. if (key == null) {
  36. return;
  37. }
  38. editor.putString(key, value);
  39. editor.commit();
  40. }
  41. public String getString(String key, String defValue) {
  42. return sp.getString(key, defValue);
  43. }
  44. public Set<String> getStringSet(String key, Set<String> defValue) {
  45. return sp.getStringSet(key, defValue);
  46. }
  47. public void putInt(String key, int value) {
  48. editor.putInt(key, value);
  49. editor.commit();
  50. }
  51. public int getInt(String key, int defValue) {
  52. return sp.getInt(key, defValue);
  53. }
  54. public Map<String, ?> getAll() {
  55. return sp.getAll();
  56. }
  57. public void remove(String key) {
  58. sp.edit().remove(key).apply();
  59. }
  60. }