Android records using MMKV

  • 2021-12-21 04:53:45
  • OfStack

Preface

I heard that Tencent's mmkv is very cowhide and can replace SharedPreferences. It is mainly used to save settings, such as string number, baud rate, camera preview angle, etc. Try Ha O (↓ _ ↓) O Ha ha ~

1. Dependency introduction, app build. gradle


implementation 'com.tencent:mmkv-static:1.0.23'

2. Encapsulate classes


import android.content.Context;

import com.tencent.mmkv.MMKV;

public class SharedPreferencesManager {


    private static MMKV kv;

    public static void init(Context context) {
        String rootDir = MMKV.initialize(context);
        System.out.println("mmkv root: " + rootDir);
        kv = MMKV.defaultMMKV();
    }

    public static void putBoolean(String key, boolean value) {
        kv.encode(key, value);
    }

    public static Boolean getBoolean(String key) {
        return kv.decodeBool(key, false);
    }

    public static Boolean getBoolean(String key, boolean defValue) {
        return kv.decodeBool(key, defValue);
    }

    public static void putInteger(String key, int value) {
        kv.encode(key, value);
    }

    public static int getInteger(String key) {
        return kv.decodeInt(key, 1);
    }

    public static int getInteger(String key, int defValue) {
        return kv.decodeInt(key, defValue);
    }

    public static void putString(String key, String value) {
        kv.encode(key, value);
    }

    public static String getString(String key) {
        return kv.decodeString(key, "");
    }

    public static String getString(String key, String defaultValue) {
        return kv.decodeString(key, defaultValue);
    }


}

3. Initialize in a custom application


public class XXApplication extends Application {

			   @Override
   			   public void onCreate() {
        	   super.onCreate();
 				    /* Initialization SharedPreferences*/
            SharedPreferencesManager.init(this);
		
    		}
}

4. Use it to your heart's content


        String mcuPath = SharedPreferencesManager.getString(Constants.SP_KEY_COM_MCU, Constants.DEFAULT_COM_MCU);
      SharedPreferencesManager.putString(Constants.SP_KEY_COM_MCU, mcuPath);


Related articles: