A little introduction

SharedPreference is a simple and lightweight file storage in The Android system. It is a persistent storage method, which is stored under the map root tag in XML by name/value pair (NVP) mechanism. As the name suggests, it is suitable for storing some simple data. For storing data types such as Int, long, Boolean, String, Float, and Set, the saved XML file can be found in the directory data/data/ application /shared_prefs.

Basic usage mode

  • Gets a SharedPreference object
SharedPreferences sp = context.getSharedPreferences(PREFERENCES_NAME,Context.MODE_PRIVATE);
Copy the code
  • Get SharedPreferences. Editor
SharedPreferences.Editor edit = sp.edit();
Copy the code
  • Store the data
edit.putString(String key,String value);
edit.putStringSet(String key, Set<String> values);
edit.putLong(String key,long value);
edit.putFloat(String key,floatvalue); edit.putBoolean(String key,boolean value); edit.putInt(String key,int value); edit.commit(); ANR edit.apply(); ANR edit.apply(); // Write asynchronous, do not care about the result, official recommendation, speed and performance is goodCopy the code
  • To get the data
sp.getString(String key,String value);
sp.getStringSet(String key, Set<String> values);
sp.getLong(String key,long value);
sp.getFloat(String key,float value);
sp.getBoolean(String key,boolean value);
sp.getInt(String key,int value);
Copy the code

These basic use methods should not be repetitive to introduce, this article mainly discusses some SP storage optimization suggestions 😝, the following is my own SP read and write performance test, for reference only:

Time-consuming statistics

storage Data article number Take/ms
Many times the commit 1000 15052
Once the commit 1000 24
The apply for many times 1000 588
Once the apply 1000 12
json 1000 73

PutString () is used for time statistics. In terms of time statistics, it is obvious that frequent commit and apply operations are time-consuming, so the solution of lag is also called out. In terms of usage, the difference between using COMMIT and apply is that both save data, but the performance and time consumption are slightly different. In terms of data format, the performance difference between JSON files and simple KV data. Here are some suggestions based on the results:

Suggestions for optimization

  • It is recommended to initialize in the Application by overriding attachBaseContext(), passing the context argument directly to the Application object.
  • It is better to use singletons instead of fetching Sp objects from the system every time, reducing overhead.
  • If MultiDex is used in the project and subcontracting exists, initialize it before subcontracting, that is, before multidex.install (), or during MultiDex execution. At this time, CPU is not fully utilized, and we cannot make full use of CPU. If we perform some operations before Multidex, we are likely to crash directly in four versions because the classes of such operations or related classes are not in our main dex. But because sharePreference does not produce such crashes, it is a class of the system.
  • Please do not use SharedPreference to store large files and a large number of keys and values, as this will cause interface lag or ANR to take up memory. Remember that it is simple storage. If you have similar requirements, please consider database, disk file storage, etc.
  • It is recommended to use Apply for storage, which is also the official recommendation. When reading into memory, since it is written to disk asynchronously, it is more efficient than commit. Commit should be used if you need to store state or save and play.
  • Do not use apply and commit frequently. If such problems exist, combine apply and commit once. For example, encapsulate the combination of a Map and commit once, because SharedPreference may have I/O bottlenecks and poor lock performance.
  • Try not to store Json and HTML, data can be less, do not worry, a large number of words please give up.
  • Do not store all data in one file. Different types of files or data can be stored in multiple files instead of one large file, which improves the reading speed.
  • Do not use the MULTI_PROCESS flag for cross-process operations, but use interprocess communication such as contentprovide.
  • If your project requires very high storage performance, you can consider abandoning the SP storage of the system, and recommend you to use Tencent’s high-performance componentsMMKV, currently over 8.8K + star.

SP utility class

Encapsulation is a modification based on AndroidUtilCode, adding a Map commit and apply. Use the SpHelpUtils helper class directly, copy and paste if necessary, to reduce the time to jump to GitHub, programmers should be lazy to the limit.

/** * description:SpUtils encapsulates the utility class. Pass getApplicationContext()) */ public class SpHelpUtils {/** * private static SpUtils sDefaultSpUtils; /** * Set the default instance of {@link SpUtils}. * * @param spUtils The default instance of {@link SpUtils}. */ public  static voidsetDefaultSpUtils(final SpUtils spUtils) {
        sDefaultSpUtils = spUtils;
    }

    /**
     * Put the string value insp. * * @param key The key of sp. * @param value The value of sp. */ public static void put(@NonNull final String key, final String value) { put(key, value, getDefaultSpUtils()); } /** * public static void put(@notnull final map <String, Object> hashmap) { put(hashmap, getDefaultSpUtils()); } /** * Put the string valuein sp.
     *
     * @param key      The key of sp.
     * @param value    The value of sp.
     * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}*/ public static void put(@NonNull final String key, final String value, final boolean isCommit) { put(key, value, isCommit, getDefaultSpUtils()); ** * @param isCommit True to use {@link SharedPreferences#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}
     */
    public static void put(final Map<String, Object> hashmap, final boolean isCommit) {
        put(hashmap, isCommit, getDefaultSpUtils());
    }


    /**
     * Return the string value in sp.
     *
     * @param key The key of sp.
     * @return the string value if sp exists or {@code ""} otherwise
     */
    public static String getString(@NonNull final String key) {
        return getString(key, getDefaultSpUtils());
    }

    /**
     * Return the string value in sp.
     *
     * @param key          The key of sp.
     * @param defaultValue The default value if the sp doesn't exist. * @return the string value if sp exists or {@code defaultValue} otherwise */ public static String getString(@NonNull final String key, final String defaultValue) { return getString(key, defaultValue, getDefaultSpUtils()); } /** * Put the int value in sp. * * @param key The key of sp. * @param value The value of sp. */ public static void put(@NonNull final String key, final int value) { put(key, value, getDefaultSpUtils()); } /** * Put the int value in sp. * * @param key The key of sp. * @param value The value of sp. * @param isCommit True to  use {@link SharedPreferences.Editor#commit()}, * false to use {@link SharedPreferences.Editor#apply()} */ public static void put(@NonNull final String key, final int value, final boolean isCommit) { put(key, value, isCommit, getDefaultSpUtils()); } /** * Return the int value in sp. * * @param key The key of sp. * @return the int value if sp exists or {@code -1} otherwise */ public static int getInt(@NonNull final String key) { return getInt(key, getDefaultSpUtils()); } /** * Return the int value in sp. * * @param key The key of sp. * @param defaultValue The default value if the sp doesn't exist.
     * @return the int value if sp exists or {@code defaultValue} otherwise
     */
    public static int getInt(@NonNull final String key, final int defaultValue) {
        return getInt(key, defaultValue, getDefaultSpUtils());
    }

    /**
     * Put the long value in sp.
     *
     * @param key   The key of sp.
     * @param value The value of sp.
     */
    public static void put(@NonNull final String key, final long value) {
        put(key, value, getDefaultSpUtils());
    }

    /**
     * Put the long value in sp.
     *
     * @param key      The key of sp.
     * @param value    The value of sp.
     * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}
     */
    public static void put(@NonNull final String key, final long value, final boolean isCommit) {
        put(key, value, isCommit, getDefaultSpUtils());
    }

    /**
     * Return the long value in sp.
     *
     * @param key The key of sp.
     * @return the long value if sp exists or {@code -1} otherwise
     */
    public static long getLong(@NonNull final String key) {
        return getLong(key, getDefaultSpUtils());
    }

    /**
     * Return the long value in sp.
     *
     * @param key          The key of sp.
     * @param defaultValue The default value if the sp doesn't exist. * @return the long value if sp exists or {@code defaultValue} otherwise */ public static long getLong(@NonNull  final String key, final long defaultValue) { return getLong(key, defaultValue, getDefaultSpUtils()); } /** * Put the float value in sp. * * @param key The key of sp. * @param value The value of sp. */ public static void put(@NonNull final String key, final float value) { put(key, value, getDefaultSpUtils()); } /** * Put the float value in sp. * * @param key The key of sp. * @param value The value of sp. * @param isCommit True to use {@link SharedPreferences.Editor#commit()}, * false to use {@link SharedPreferences.Editor#apply()} */ public static void put(@NonNull final String key, final float value, final boolean isCommit) { put(key, value, isCommit, getDefaultSpUtils()); } /** * Return the float value in sp. * * @param key The key of sp. * @return the float value if sp exists or {@code -1f} otherwise */ public static float getFloat(@NonNull final String key) { return getFloat(key, getDefaultSpUtils()); } /** * Return the float value in sp. * * @param key The key of sp. * @param defaultValue The default value if the sp doesn't exist.
     * @return the float value if sp exists or {@code defaultValue} otherwise
     */
    public static float getFloat(@NonNull final String key, final float defaultValue) {
        return getFloat(key, defaultValue, getDefaultSpUtils());
    }

    /**
     * Put the boolean value in sp.
     *
     * @param key   The key of sp.
     * @param value The value of sp.
     */
    public static void put(@NonNull final String key, final boolean value) {
        put(key, value, getDefaultSpUtils());
    }

    /**
     * Put the boolean value in sp.
     *
     * @param key      The key of sp.
     * @param value    The value of sp.
     * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}
     */
    public static void put(@NonNull final String key, final boolean value, final boolean isCommit) {
        put(key, value, isCommit, getDefaultSpUtils());
    }

    /**
     * Return the boolean value in sp.
     *
     * @param key The key of sp.
     * @return the boolean value if sp exists or {@code false} otherwise
     */
    public static boolean getBoolean(@NonNull final String key) {
        return getBoolean(key, getDefaultSpUtils());
    }

    /**
     * Return the boolean value in sp.
     *
     * @param key          The key of sp.
     * @param defaultValue The default value if the sp doesn't exist.
     * @return the boolean value if sp exists or {@code defaultValue} otherwise
     */
    public static boolean getBoolean(@NonNull final String key, final boolean defaultValue) {
        return getBoolean(key, defaultValue, getDefaultSpUtils());
    }

    /**
     * Put the set of string value in sp.
     *
     * @param key   The key of sp.
     * @param value The value of sp.
     */
    public static void put(@NonNull final String key, final Set<String> value) {
        put(key, value, getDefaultSpUtils());
    }

    /**
     * Put the set of string value in sp.
     *
     * @param key      The key of sp.
     * @param value    The value of sp.
     * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}
     */
    public static void put(@NonNull final String key,
                           final Set<String> value,
                           final boolean isCommit) {
        put(key, value, isCommit, getDefaultSpUtils());
    }

    /**
     * Return the set of string value in sp.
     *
     * @param key The key of sp.
     * @return the set of string value if sp exists
     * or {@code Collections.<String>emptySet()} otherwise
     */
    public static Set<String> getStringSet(@NonNull final String key) {
        return getStringSet(key, getDefaultSpUtils());
    }

    /**
     * Return the set of string value in sp.
     *
     * @param key          The key of sp.
     * @param defaultValue The default value if the sp doesn't exist.
     * @return the set of string value if sp exists or {@code defaultValue} otherwise
     */
    public static Set<String> getStringSet(@NonNull final String key,
                                           final Set<String> defaultValue) {
        return getStringSet(key, defaultValue, getDefaultSpUtils());
    }

    /**
     * Return all values in sp.
     *
     * @return all values insp */ public static Map<String, ? >getAll() {
        return getAll(getDefaultSpUtils());
    }

    /**
     * Return whether the sp contains the preference.
     *
     * @param key The key of sp.
     * @return {@code true}: yes<br>{@code false}: no
     */
    public static boolean contains(@NonNull final String key) {
        return contains(key, getDefaultSpUtils());
    }

    /**
     * Remove the preference in sp.
     *
     * @param key The key of sp.
     */
    public static void remove(@NonNull final String key) {
        remove(key, getDefaultSpUtils());
    }

    /**
     * Remove the preference in sp.
     *
     * @param key      The key of sp.
     * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}
     */
    public static void remove(@NonNull final String key, final boolean isCommit) {
        remove(key, isCommit, getDefaultSpUtils());
    }

    /**
     * Remove all preferences in sp.
     */
    public static void clear() {
        clear(getDefaultSpUtils());
    }

    /**
     * Remove all preferences in sp.
     *
     * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}
     */
    public static void clear(final boolean isCommit) {
        clear(isCommit, getDefaultSpUtils());
    }

    ///////////////////////////////////////////////////////////////////////////
    // dividing line
    ///////////////////////////////////////////////////////////////////////////

    /**
     * Put the string value insp. * * @param key The key of sp. * @param value The value of sp. * @param spUtils The instance of {@link SpUtils}. */ public static void put(@NonNull final String key, final String value, @NonNull final SpUtils spUtils) { spUtils.put(key, value); } @param spUtils The instance of {@link spUtils}. */ public static void put(@nonnull final Map<String, Object> map, @NonNull final SpUtils spUtils) { spUtils.put(map); } /** * Put the string valuein sp.
     *
     * @param key      The key of sp.
     * @param value    The value of sp.
     * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}* @param spUtils The instance of {@link SpUtils}. */ public static void put(@NonNull final String key, final String value, final boolean isCommit, @NonNull final SpUtils spUtils) { spUtils.put(key, value, isCommit); } @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}
     * @param spUtils  The instance of {@link SpUtils}.
     */
    public static void put(@NonNull final Map<String, Object> map, final boolean isCommit, @NonNull final SpUtils spUtils) {
        spUtils.put(map, isCommit);
    }

    /**
     * Return the string value in sp.
     *
     * @param key     The key of sp.
     * @param spUtils The instance of {@link SpUtils}.
     * @return the string value if sp exists or {@code ""} otherwise
     */
    public static String getString(@NonNull final String key, @NonNull final SpUtils spUtils) {
        return spUtils.getString(key);
    }

    /**
     * Return the string value in sp.
     *
     * @param key          The key of sp.
     * @param defaultValue The default value if the sp doesn't exist. * @param spUtils The instance of {@link SpUtils}. * @return the string value if sp exists or {@code defaultValue} otherwise */ public static String getString(@NonNull final String key, final String defaultValue, @NonNull final SpUtils spUtils) { return spUtils.getString(key, defaultValue); } /** * Put the int value in sp. * * @param key The key of sp. * @param value The value of sp. * @param spUtils The instance of {@link SpUtils}. */ public static void put(@NonNull final String key, final int value, @NonNull final SpUtils spUtils) { spUtils.put(key, value); } /** * Put the int value in sp. * * @param key The key of sp. * @param value The value of sp. * @param isCommit True to  use {@link SharedPreferences.Editor#commit()}, * false to use {@link SharedPreferences.Editor#apply()} * @param spUtils The instance of {@link SpUtils}. */ public static void put(@NonNull final String key, final int value, final boolean isCommit, @NonNull final SpUtils spUtils) { spUtils.put(key, value, isCommit); } /** * Return the int value in sp. * * @param key The key of sp. * @param spUtils The instance of {@link SpUtils}. * @return the int value if sp exists or {@code -1} otherwise */ public static int getInt(@NonNull final String key, @NonNull final SpUtils spUtils) { return spUtils.getInt(key); } /** * Return the int value in sp. * * @param key The key of sp. * @param defaultValue The default value if the sp doesn't exist.
     * @param spUtils      The instance of {@link SpUtils}.
     * @return the int value if sp exists or {@code defaultValue} otherwise
     */
    public static int getInt(@NonNull final String key, final int defaultValue, @NonNull final SpUtils spUtils) {
        return spUtils.getInt(key, defaultValue);
    }

    /**
     * Put the long value in sp.
     *
     * @param key     The key of sp.
     * @param value   The value of sp.
     * @param spUtils The instance of {@link SpUtils}.
     */
    public static void put(@NonNull final String key, final long value, @NonNull final SpUtils spUtils) {
        spUtils.put(key, value);
    }

    /**
     * Put the long value in sp.
     *
     * @param key      The key of sp.
     * @param value    The value of sp.
     * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}
     * @param spUtils  The instance of {@link SpUtils}.
     */
    public static void put(@NonNull final String key,
                           final long value,
                           final boolean isCommit,
                           @NonNull final SpUtils spUtils) {
        spUtils.put(key, value, isCommit);
    }

    /**
     * Return the long value in sp.
     *
     * @param key     The key of sp.
     * @param spUtils The instance of {@link SpUtils}.
     * @return the long value if sp exists or {@code -1} otherwise
     */
    private static long getLong(@NonNull final String key, @NonNull final SpUtils spUtils) {
        return spUtils.getLong(key);
    }

    /**
     * Return the long value in sp.
     *
     * @param key          The key of sp.
     * @param defaultValue The default value if the sp doesn't exist.
     * @param spUtils      The instance of {@link SpUtils}.
     * @return the long value if sp exists or {@code defaultValue} otherwise
     */
    private static long getLong(@NonNull final String key, final long defaultValue, @NonNull final SpUtils spUtils) {
        return spUtils.getLong(key, defaultValue);
    }

    /**
     * Put the float value in sp.
     *
     * @param key     The key of sp.
     * @param value   The value of sp.
     * @param spUtils The instance of {@link SpUtils}.
     */
    public static void put(@NonNull final String key, final float value, @NonNull final SpUtils spUtils) {
        spUtils.put(key, value);
    }

    /**
     * Put the float value in sp.
     *
     * @param key      The key of sp.
     * @param value    The value of sp.
     * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}
     * @param spUtils  The instance of {@link SpUtils}.
     */
    public static void put(@NonNull final String key,
                           final float value,
                           final boolean isCommit,
                           @NonNull final SpUtils spUtils) {
        spUtils.put(key, value, isCommit);
    }

    /**
     * Return the float value in sp.
     *
     * @param key     The key of sp.
     * @param spUtils The instance of {@link SpUtils}.
     * @return the float value if sp exists or {@code -1f} otherwise
     */
    private static float getFloat(@NonNull final String key, @NonNull final SpUtils spUtils) {
        return spUtils.getFloat(key);
    }

    /**
     * Return the float value in sp.
     *
     * @param key          The key of sp.
     * @param defaultValue The default value if the sp doesn't exist.
     * @param spUtils      The instance of {@link SpUtils}.
     * @return the float value if sp exists or {@code defaultValue} otherwise
     */
    private static float getFloat(@NonNull final String key, final float defaultValue, @NonNull final SpUtils spUtils) {
        return spUtils.getFloat(key, defaultValue);
    }

    /**
     * Put the boolean value in sp.
     *
     * @param key     The key of sp.
     * @param value   The value of sp.
     * @param spUtils The instance of {@link SpUtils}.
     */
    public static void put(@NonNull final String key, final boolean value, @NonNull final SpUtils spUtils) {
        spUtils.put(key, value);
    }

    /**
     * Put the boolean value in sp.
     *
     * @param key      The key of sp.
     * @param value    The value of sp.
     * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}
     * @param spUtils  The instance of {@link SpUtils}.
     */
    public static void put(@NonNull final String key,
                           final boolean value,
                           final boolean isCommit,
                           @NonNull final SpUtils spUtils) {
        spUtils.put(key, value, isCommit);
    }

    /**
     * Return the boolean value in sp.
     *
     * @param key     The key of sp.
     * @param spUtils The instance of {@link SpUtils}.
     * @return the boolean value if sp exists or {@code false} otherwise
     */
    public static boolean getBoolean(@NonNull final String key, @NonNull final SpUtils spUtils) {
        return spUtils.getBoolean(key);
    }

    /**
     * Return the boolean value in sp.
     *
     * @param key          The key of sp.
     * @param defaultValue The default value if the sp doesn't exist.
     * @param spUtils      The instance of {@link SpUtils}.
     * @return the boolean value if sp exists or {@code defaultValue} otherwise
     */
    public static boolean getBoolean(@NonNull final String key,
                                     final boolean defaultValue,
                                     @NonNull final SpUtils spUtils) {
        return spUtils.getBoolean(key, defaultValue);
    }

    /**
     * Put the set of string value in sp.
     *
     * @param key     The key of sp.
     * @param value   The value of sp.
     * @param spUtils The instance of {@link SpUtils}.
     */
    public static void put(@NonNull final String key, final Set<String> value, @NonNull final SpUtils spUtils) {
        spUtils.put(key, value);
    }

    /**
     * Put the set of string value in sp.
     *
     * @param key      The key of sp.
     * @param value    The value of sp.
     * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}
     * @param spUtils  The instance of {@link SpUtils}.
     */
    public static void put(@NonNull final String key,
                           final Set<String> value,
                           final boolean isCommit,
                           @NonNull final SpUtils spUtils) {
        spUtils.put(key, value, isCommit);
    }

    /**
     * Return the set of string value in sp.
     *
     * @param key     The key of sp.
     * @param spUtils The instance of {@link SpUtils}.
     * @return the set of string value if sp exists
     * or {@code Collections.<String>emptySet()} otherwise
     */
    private static Set<String> getStringSet(@NonNull final String key, @NonNull final SpUtils spUtils) {
        return spUtils.getStringSet(key);
    }

    /**
     * Return the set of string value in sp.
     *
     * @param key          The key of sp.
     * @param defaultValue The default value if the sp doesn't exist.
     * @param spUtils      The instance of {@link SpUtils}.
     * @return the set of string value if sp exists or {@code defaultValue} otherwise
     */
    private static Set<String> getStringSet(@NonNull final String key,
                                            final Set<String> defaultValue,
                                            @NonNull final SpUtils spUtils) {
        return spUtils.getStringSet(key, defaultValue);
    }

    /**
     * Return all values in sp.
     *
     * @param spUtils The instance of {@link SpUtils}.
     * @return all values insp */ private static Map<String, ? > getAll(@NonNull final SpUtils spUtils) {return spUtils.getAll();
    }

    /**
     * Return whether the sp contains the preference.
     *
     * @param key     The key of sp.
     * @param spUtils The instance of {@link SpUtils}.
     * @return {@code true}: yes<br>{@code false}: no
     */
    public static boolean contains(@NonNull final String key, @NonNull final SpUtils spUtils) {
        return spUtils.contains(key);
    }

    /**
     * Remove the preference in sp.
     *
     * @param key     The key of sp.
     * @param spUtils The instance of {@link SpUtils}.
     */
    public static void remove(@NonNull final String key, @NonNull final SpUtils spUtils) {
        spUtils.remove(key);
    }

    /**
     * Remove the preference in sp.
     *
     * @param key      The key of sp.
     * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}
     * @param spUtils  The instance of {@link SpUtils}.
     */
    public static void remove(@NonNull final String key, final boolean isCommit, @NonNull final SpUtils spUtils) {
        spUtils.remove(key, isCommit);
    }

    /**
     * Remove all preferences in sp.
     *
     * @param spUtils The instance of {@link SpUtils}.
     */
    public static void clear(@NonNull final SpUtils spUtils) {
        spUtils.clear();
    }

    /**
     * Remove all preferences in sp.
     *
     * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}* @param spUtils The instance of {@link SpUtils}. */ public static void clear(final boolean isCommit, @NonNull final SpUtils spUtils) { spUtils.clear(isCommit); } /** * get the simple storage utility class SpUtils ** @return SpUtils
     */
    private static SpUtils getDefaultSpUtils() {
        returnsDefaultSpUtils ! = null ? sDefaultSpUtils : SpUtils.getInstance(getApplicationByReflect()); } /** * if you do not initialize the utility class, then I will get the current applicationContext() ** @ via reflectionreturn Application
     */
    private static Application getApplicationByReflect() {
        try {
            @SuppressLint("PrivateApi") Class<? > activityThread = Class.forName("android.app.ActivityThread");
            Object thread = activityThread.getMethod("currentActivityThread").invoke(null);
            Object app = activityThread.getMethod("getApplication").invoke(thread);
            if (app == null) {
                throw new NullPointerException("u should init first");
            }
            return (Application) app;
        } catch (NoSuchMethodException | IllegalAccessException | ClassNotFoundException | InvocationTargetException e) {
            e.printStackTrace();
        }
        throw new NullPointerException("u should init first"); }}Copy the code
public class SpUtils {
    private static final Map<String, SpUtils> SP_UTILS_MAP = new HashMap<>();
    private SharedPreferences sp;

    /**
     * Return the single {@link SpUtils} instance
     *
     * @param context context
     * @return the single {@link SpUtils} instance
     */
    public static SpUtils getInstance(Context context) {
        return getInstance(context, "", Context.MODE_PRIVATE);
    }

    /**
     * Return the single {@link SpUtils} instance
     *
     * @param context context
     * @param mode    Operating mode.
     * @return the single {@link SpUtils} instance
     */
    public static SpUtils getInstance(Context context, final int mode) {
        return getInstance(context, "", mode);
    }

    /**
     * Return the single {@link SpUtils} instance
     *
     * @param context context
     * @param spName  The name of sp.
     * @return the single {@link SpUtils} instance
     */
    public static SpUtils getInstance(Context context, String spName) {
        return getInstance(context, spName, Context.MODE_PRIVATE);
    }

    /**
     * Return the single {@link SpUtils} instance
     *
     * @param context context
     * @param spName  The name of sp.
     * @param mode    Operating mode.
     * @return the single {@link SpUtils} instance
     */
    public static SpUtils getInstance(Context context, String spName, final int mode) {
        if (context == null) {
            throw new UnsupportedOperationException("context can't empty, please init me in SpHelpUtils.class");
        }
        if (isSpace(spName)) {
            spName = context.getPackageName() + "_preferences";
        }
        SpUtils spUtils = SP_UTILS_MAP.get(spName);
        if (spUtils == null) {
            synchronized (SpUtils.class) {
                spUtils = SP_UTILS_MAP.get(spName);
                if(spUtils == null) { spUtils = new SpUtils(context, spName, mode); SP_UTILS_MAP.put(spName, spUtils); }}}return spUtils;
    }

    private SpUtils(Context context, final String spName) {
        sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
    }

    private SpUtils(final Context context, final String spName, final int mode) {
        sp = context.getSharedPreferences(spName, mode);
    }

    /**
     * Put the string value insp. * * @param key The key of sp. * @param value The value of sp. */ public void put(@NonNull final String key, Final String value) {// TODO Due to the functional requirements of the project, the flag bits of this place are changed to commit mode, and later need to be optimized one by one into apply PUT (key, value,true); } /** * Commit Map combination for one-time commit or apply, Public void put(@nonnull final map <String, Object> map) {put(map,true);
    }

    /**
     * Put the string value in sp.
     *
     * @param key      The key of sp.
     * @param value    The value of sp.
     * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}
     */
    public void put(@NonNull final String key, final String value, final boolean isCommit) {
        if (isCommit) {
            sp.edit().putString(key, value).commit();
        } else{ sp.edit().putString(key, value).apply(); } /** * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}
     */
    public void put(@NonNull final Map<String, Object> map, final boolean isCommit) {
        SharedPreferences.Editor edit = sp.edit();
        for (Map.Entry<String, Object> next : map.entrySet()) {
         if (next.getValue() == null) {
                continue;
            }
            if (next.getValue() instanceof String) {
                edit.putString(next.getKey(), String.valueOf(next.getValue()));
            } else if (next.getValue() instanceof Boolean) {
                edit.putBoolean(next.getKey(), (Boolean) next.getValue());
            } else if (next.getValue() instanceof Integer) {
                edit.putInt(next.getKey(), (Integer) next.getValue());
            } else if (next.getValue() instanceof Float) {
                edit.putFloat(next.getKey(), (Float) next.getValue());
            } else if (next.getValue() instanceof Long) {
                edit.putLong(next.getKey(), (Long) next.getValue());
            } else {
                throw new UnsupportedOperationException("parameter Unsupported type!"); }}if (isCommit) {
            edit.commit();
        } else {
            edit.apply();
        }
    }

    /**
     * Return the string value in sp.
     *
     * @param key The key of sp.
     * @return the string value if sp exists or {@code ""} otherwise
     */
    public String getString(@NonNull final String key) {
        return getString(key, "");
    }

    /**
     * Return the string value in sp.
     *
     * @param key          The key of sp.
     * @param defaultValue The default value if the sp doesn't exist. * @return the string value if sp exists or {@code defaultValue} otherwise */ public String getString(@NonNull final String key, final String defaultValue) { return sp.getString(key, defaultValue); } /** * Put the int value in sp. * * @param key The key of sp. * @param value The value of sp. */ public void put(@NonNull final String key, final int value) { put(key, value, false); } /** * Put the int value in sp. * * @param key The key of sp. * @param value The value of sp. * @param isCommit True to  use {@link SharedPreferences.Editor#commit()}, * false to use {@link SharedPreferences.Editor#apply()} */ public void put(@NonNull final String key, final int value, final boolean isCommit) { if (isCommit) { sp.edit().putInt(key, value).commit(); } else { sp.edit().putInt(key, value).apply(); } } /** * Return the int value in sp. * * @param key The key of sp. * @return the int value if sp exists or {@code -1} otherwise */ public int getInt(@NonNull final String key) { return getInt(key, -1); } /** * Return the int value in sp. * * @param key The key of sp. * @param defaultValue The default value if the sp doesn't exist.
     * @return the int value if sp exists or {@code defaultValue} otherwise
     */
    public int getInt(@NonNull final String key, final int defaultValue) {
        return sp.getInt(key, defaultValue);
    }

    /**
     * Put the long value in sp.
     *
     * @param key   The key of sp.
     * @param value The value of sp.
     */
    public void put(@NonNull final String key, final long value) {
        put(key, value, false);
    }

    /**
     * Put the long value in sp.
     *
     * @param key      The key of sp.
     * @param value    The value of sp.
     * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}
     */
    public void put(@NonNull final String key, final long value, final boolean isCommit) {
        if (isCommit) {
            sp.edit().putLong(key, value).commit();
        } else {
            sp.edit().putLong(key, value).apply();
        }
    }

    /**
     * Return the long value in sp.
     *
     * @param key The key of sp.
     * @return the long value if sp exists or {@code -1} otherwise
     */
    public long getLong(@NonNull final String key) {
        return getLong(key, -1L);
    }

    /**
     * Return the long value in sp.
     *
     * @param key          The key of sp.
     * @param defaultValue The default value if the sp doesn't exist.
     * @return the long value if sp exists or {@code defaultValue} otherwise
     */
    public long getLong(@NonNull final String key, final long defaultValue) {
        return sp.getLong(key, defaultValue);
    }

    /**
     * Put the float value in sp.
     *
     * @param key   The key of sp.
     * @param value The value of sp.
     */
    public void put(@NonNull final String key, final float value) {
        put(key, value, false);
    }

    /**
     * Put the float value in sp.
     *
     * @param key      The key of sp.
     * @param value    The value of sp.
     * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}
     */
    public void put(@NonNull final String key, final float value, final boolean isCommit) {
        if (isCommit) {
            sp.edit().putFloat(key, value).commit();
        } else {
            sp.edit().putFloat(key, value).apply();
        }
    }

    /**
     * Return the float value in sp.
     *ll final String key, final boolean value, final boolean isCommit) {
        if (isCommit) {
            sp.edit().putBoolean(key, value).commit();
        } else {
            sp.edit().putBoolean(key, value).apply();
        }
    }

    /**
     * Return the boolean value in sp.
     *
     * @param key The key of sp.
     * @return the boolean value if sp exists or {@code false} otherwise
     */
    public boolean getBoolean(@NonNull final String key) {
        return getBoolean(key, false);
    }

    /**
     * Return the boolean value in sp.
     *
     * @param key          The key of sp.
     * @param defaultValue The default value if the sp doesn't exist.
     * @return the boolean value if sp exists or {@code defaultValue} otherwise
     */
    public boolean getBoolean(@NonNull final String key, final boolean defaultValue) {
        return sp.getBoolean(key, defaultValue);
    }

    /**
     * Put the set of string value in sp.
     *
     * @param key   The key of sp.
     * @param value The value of sp.
     */
    public void put(@NonNull final String key, final Set<String> value) {
        put(key, value, false);
    }

    /**
     * Put the set of string value in sp.
     *
     * @param key      The key of sp.
     * @param value    The value of sp.
     * @param isCommit True to use {@link SharedPreferences.Editor#commit()},
     *                 false to use {@link SharedPreferences.Editor#apply()}
     */
    public void put(@NonNull final String key,
                    final Set<String> value,
                    final boolean isCommit) {
        if (isCommit) {
            sp.edit().putStringSet(key, value).commit();
        } else {
            sp.edit().putStringSet(key, value).apply();
        }
    }

    /**
     * Return the set of string value in sp.
     *
     * @param key The key of sp.
     * @return the set of string value ifsp exists * or {@code Collections.<String>emptySet()} otherwise */ public Set<String> getStringSet(@NonNull final String  key) {return getStringSet(key, Collections.emptySet());
    }

    /**
     * Return the set of string value in sp.
     *
     * @param key          The key of sp.
     * @param defaultValue The default value if the sp doesn't exist. * @return the set of string value if sp exists or {@code defaultValue} otherwise */ public Set
      
        getStringSet(@NonNull final String key, final Set
       
         defaultValue) { return sp.getStringSet(key, defaultValue); } /** * Return all values in sp. * * @return all values in sp */ public Map
        
          getAll() { return sp.getAll(); } /** * Return whether the sp contains the preference. * * @param key The key of sp. * @return {@code true}: yes
         

{@code false}: no */ public boolean contains(@NonNull final String key) { return sp.contains(key); } /** * Remove the preference in sp. * * @param key The key of sp. */ public void remove(@NonNull final String key) { remove(key, false); } /** * Remove the preference in sp. * * @param key The key of sp. * @param isCommit True to use {@link SharedPreferences.Editor#commit()}, * false to use {@link SharedPreferences.Editor#apply()} */ public void remove(@NonNull final String key, final boolean isCommit) { if (isCommit) { sp.edit().remove(key).commit(); } else { sp.edit().remove(key).apply(); } } /** * Remove all preferences in sp. */ public void clear() { clear(false); } /** * Remove all preferences in sp. * * @param isCommit True to use {@link SharedPreferences.Editor#commit()}, * false to use {@link SharedPreferences.Editor#apply()} */ public void clear(final boolean isCommit) { if (isCommit) { sp.edit().clear().commit(); } else { sp.edit().clear().apply(); } } private static boolean isSpace(final String s) { if (s == null) { return true; } for (int i = 0, len = s.length(); i < len; ++i) { if (! Character.isWhitespace(s.charAt(i))) { return false; } } return true; }}
,>
Copy the code

Write in the last

Thank you for your reading. If you have any deficiencies or better suggestions, please leave a message and reply. I will try to improve the quality of the article to share it with more readers.