For iOS, please go to juejin.cn/post/696680…

Reason for use: SharedPreferences multithreaded value invalid, a bear brother recommended the use of MMKV storage sharps, not incense loss. However, I hold the mentality of losing money to play, really sweet!!

MMKV advantage

  • Use one of the zero-copy techniquesmmapMemory mapped key-value component. User space can share data from kernel space, reducing the number of copies from kernel space to user space
  • Use the best performanceprotobufagreement
  • Stable, first used on iOS, and later on Android can also use this really fragrant tool
  • Support SharedPreferences migration to MMKV
  • Performance is better than SharedPreferences

Then start playing

Add the dependent

Build. Gradle with dependencies, you can visit the Github project at github.com/Tencent/MMK…

Dependencies {implementation 'com. Tencent :mmkv-static:1.2.8'}Copy the code

Initialize MMKV

You can initialize the MMKV on onCreate

@Override
public void onCreate() {
    super.onCreate();
    MMKV.initialize(this);
}
Copy the code

Smells good use

import com.tencent.mmkv.MMKV; // Create default instance MMKV kv = mmkv.defaultmmkv (); MMKV kv2 = mmKV.mmkvWithID ("test", mmKV.multi_process_mode); // Set value Boolean value kv.encode("bool", true); Boolean bValue = kv.decodebool ("bool"); Encode ("int", integer.min_value); Int iValue = kv.decodeint ("int"); // set value string kv.encode("string", "Hello from MMKV "); String STR = kv.decodeString(" String "); // set value float kv.encode("float",30f); // Get value float float floatValue = kv.decodefloat ("float"); // Set value bytes kv.encode("bytes", bytes); Bytes [] b = kv.decodebytes ("bytes"); // set value double kv.encode("double", double.min_value); // get double double d = kv.decodedouble ("double"); // set value long kv.encode("long", long.max_value); // get value long long l = kv.decodelong ("long"); Kv.encode ("set", new HashSet<String>(2) {{add("1"); add("2"); }}); Set<String> set = kv.decodestringSet ("1"); [] strArray = kv.allkeys (); Long lo = kv.totalsize (); Boolean hasBool = kv.containsKey("bool"); // Delete a single kv.removevalueForkey ("test"); Evaluesforkeys (new String[]{"test1", "test2"}); // Delete the cache value, and subsequent calls will load all key values from disk kv.clearMemoryCache(); ClearAl () kv.clearall (); clearAl() kv.clearall (); Kv.clearall (); // clearAll(); // clearAll();Copy the code