MMKV is an efficient, small, easy-to-use mobile key-value storage framework used in the WeChat application.
npx @tessl/cli install tessl/maven-com-tencent--mmkv-shared@2.2.00
# MMKV
1
2
MMKV is an efficient, high-performance key-value storage framework developed by Tencent for Android applications. It uses memory-mapped files for fast read/write operations and Protocol Buffers for serialization, providing superior performance compared to SharedPreferences while maintaining full compatibility with the SharedPreferences interface.
3
4
## Package Information
5
6
- **Package Name**: mmkv-shared
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**: `implementation 'com.tencent:mmkv-shared:2.2.2'`
10
11
## Core Imports
12
13
```java
14
import com.tencent.mmkv.MMKV;
15
import com.tencent.mmkv.MMKVLogLevel;
16
```
17
18
## Basic Usage
19
20
```java
21
import com.tencent.mmkv.MMKV;
22
23
public class MainActivity extends AppCompatActivity {
24
@Override
25
protected void onCreate(Bundle savedInstanceState) {
26
super.onCreate(savedInstanceState);
27
28
// Initialize MMKV (call once in Application.onCreate)
29
String rootDir = MMKV.initialize(this);
30
31
// Get default MMKV instance
32
MMKV kv = MMKV.defaultMMKV();
33
34
// Store values
35
kv.encode("user_name", "Alice");
36
kv.encode("user_age", 25);
37
kv.encode("is_premium", true);
38
39
// Retrieve values
40
String name = kv.decodeString("user_name", "");
41
int age = kv.decodeInt("user_age", 0);
42
boolean isPremium = kv.decodeBool("is_premium", false);
43
44
// Use as SharedPreferences drop-in replacement
45
SharedPreferences.Editor editor = kv.edit();
46
editor.putString("settings", "value").apply();
47
}
48
}
49
```
50
51
## Architecture
52
53
MMKV is built around several key components:
54
55
- **Memory-Mapped Files**: Uses mmap for efficient file I/O operations, reducing system calls and improving performance
56
- **Protocol Buffers**: Efficient binary serialization format for data storage and retrieval
57
- **Multi-Process Support**: Safe concurrent access across multiple processes with file locking mechanisms
58
- **Encryption**: Optional AES encryption for sensitive data protection
59
- **Expiration System**: Built-in key expiration functionality for automatic data cleanup
60
- **SharedPreferences Compatibility**: Drop-in replacement for Android's SharedPreferences with identical API
61
- **Namespace Support**: Custom directory organization for logical data separation
62
63
## Capabilities
64
65
### Initialization and Setup
66
67
Core initialization functionality for setting up MMKV in Android applications. Must be called before using any MMKV instances.
68
69
```java { .api }
70
public static String initialize(Context context);
71
public static String initialize(Context context, MMKVLogLevel logLevel);
72
public static String initialize(Context context, String rootDir);
73
public static String initialize(Context context, String rootDir, MMKVLogLevel logLevel);
74
public static String initialize(Context context, String rootDir, LibLoader loader, MMKVLogLevel logLevel, MMKVHandler handler);
75
```
76
77
[Initialization and Setup](./initialization.md)
78
79
### Instance Creation and Management
80
81
MMKV instance creation with various configuration options including encryption, multi-process modes, and custom storage locations.
82
83
```java { .api }
84
public static MMKV defaultMMKV();
85
public static MMKV mmkvWithID(String mmapID);
86
public static MMKV mmkvWithID(String mmapID, int mode);
87
public static MMKV mmkvWithID(String mmapID, int mode, String cryptKey);
88
public static MMKV mmkvWithID(String mmapID, int mode, String cryptKey, String rootPath, long expectedCapacity);
89
```
90
91
[Instance Management](./instance-management.md)
92
93
### Key-Value Storage Operations
94
95
Core storage operations for all supported data types including primitives, strings, byte arrays, and Parcelable objects, with optional expiration support.
96
97
```java { .api }
98
public boolean encode(String key, boolean value);
99
public boolean encode(String key, int value);
100
public boolean encode(String key, long value);
101
public boolean encode(String key, String value);
102
public boolean encode(String key, byte[] value);
103
public boolean decodeBool(String key, boolean defaultValue);
104
public int decodeInt(String key, int defaultValue);
105
public String decodeString(String key, String defaultValue);
106
```
107
108
[Storage Operations](./storage-operations.md)
109
110
### Multi-Process Support
111
112
Advanced multi-process functionality for safe concurrent access across Android processes, including inter-process locking and content change notifications.
113
114
```java { .api }
115
public void lock();
116
public void unlock();
117
public boolean tryLock();
118
public void checkContentChangedByOuterProcess();
119
public boolean isMultiProcess();
120
```
121
122
[Multi-Process Support](./multi-process.md)
123
124
### Encryption and Security
125
126
Encryption capabilities for protecting sensitive data with AES encryption, key management, and secure key rotation.
127
128
```java { .api }
129
public String cryptKey();
130
public boolean reKey(String cryptKey);
131
public void checkReSetCryptKey(String cryptKey);
132
```
133
134
[Encryption and Security](./encryption.md)
135
136
### Data Management and Maintenance
137
138
Comprehensive data management including backup/restore operations, file validation, storage cleanup, and performance optimization.
139
140
```java { .api }
141
public void clearAll();
142
public void clearAllWithKeepingSpace();
143
public void trim();
144
public long totalSize();
145
public long actualSize();
146
public boolean removeStorage(String mmapID);
147
public boolean isFileValid(String mmapID);
148
```
149
150
[Data Management](./data-management.md)
151
152
### Advanced Features
153
154
Advanced functionality including key expiration, native buffer operations, Anonymous Shared Memory support, and performance optimizations.
155
156
```java { .api }
157
public boolean enableAutoKeyExpire(int expireDurationInSecond);
158
public boolean disableAutoKeyExpire();
159
public void enableCompareBeforeSet();
160
public NativeBuffer createNativeBuffer(int size);
161
public MMKV mmkvWithAshmemID(Context context, String mmapID, int size, int mode, String cryptKey);
162
```
163
164
[Advanced Features](./advanced-features.md)
165
166
## Constants
167
168
```java { .api }
169
// Process modes
170
public static final int SINGLE_PROCESS_MODE = 1 << 0;
171
public static final int MULTI_PROCESS_MODE = 1 << 1;
172
public static final int READ_ONLY_MODE = 1 << 5;
173
174
// Expiration constants
175
public static final int ExpireNever = 0;
176
public static final int ExpireInMinute = 60;
177
public static final int ExpireInHour = 60 * 60;
178
public static final int ExpireInDay = 24 * 60 * 60;
179
public static final int ExpireInMonth = 30 * 24 * 60 * 60;
180
public static final int ExpireInYear = 365 * 30 * 24 * 60 * 60;
181
```
182
183
## Types
184
185
```java { .api }
186
// Core enums
187
public enum MMKVLogLevel {
188
LevelDebug, LevelInfo, LevelWarning, LevelError, LevelNone
189
}
190
191
public enum MMKVRecoverStrategic {
192
OnErrorDiscard, OnErrorRecover
193
}
194
195
// Callback interfaces
196
public interface MMKVHandler {
197
MMKVRecoverStrategic onMMKVCRCCheckFail(String mmapID);
198
MMKVRecoverStrategic onMMKVFileLengthError(String mmapID);
199
boolean wantLogRedirecting();
200
void mmkvLog(MMKVLogLevel level, String file, int line, String function, String message);
201
}
202
203
public interface MMKVContentChangeNotification {
204
void onContentChangedByOuterProcess(String mmapID);
205
}
206
207
// Native buffer support
208
public final class NativeBuffer {
209
public long pointer;
210
public int size;
211
public NativeBuffer(long ptr, int length);
212
}
213
214
// Library loader interface
215
public interface LibLoader {
216
void loadLibrary(String libName);
217
}
218
219
// Exception classes
220
public class UnsupportedArchitectureException extends RuntimeException {
221
public UnsupportedArchitectureException(String message);
222
}
223
```