当前位置:主页 > 移动开发 > Android代码 >

Android使用MMKV的记录

时间:2022-06-15 10:21:22 | 栏目:Android代码 | 点击:

前言

听说腾讯的mmkv很牛皮,可以替代SharedPreferences,主要用来保存设置,比如串口号、波特率、摄像头预览角度等等,来试一下哈O(∩_∩)O哈哈~

1.依赖引入,app build.gradle

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

2.封装类

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.在自定义的application中初始化

public class XXApplication extends Application {

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

4.尽情使用吧

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

您可能感兴趣的文章:

相关文章