0
# Initialization and Configuration
1
2
Core initialization methods for setting up MMKV with various configuration options including custom directories, log levels, library loaders, and error handlers.
3
4
## Capabilities
5
6
### Basic Initialization
7
8
Initialize MMKV with default configuration. Must be called once during app startup before using any MMKV instances.
9
10
```java { .api }
11
/**
12
* Initialize MMKV with default configuration.
13
* @param context The Android app context, usually from Application
14
* @return The root folder of MMKV, defaults to $(FilesDir)/mmkv
15
*/
16
public static String initialize(Context context);
17
```
18
19
**Usage Example:**
20
21
```java
22
import com.tencent.mmkv.MMKV;
23
24
public class MyApplication extends Application {
25
@Override
26
public void onCreate() {
27
super.onCreate();
28
// Initialize MMKV once during app startup
29
String rootDir = MMKV.initialize(this);
30
Log.d("MMKV", "MMKV root directory: " + rootDir);
31
}
32
}
33
```
34
35
### Initialization with Custom Log Level
36
37
Initialize MMKV with a custom log level for debugging and production environments.
38
39
```java { .api }
40
/**
41
* Initialize MMKV with customize log level.
42
* @param context The Android app context
43
* @param logLevel The log level of MMKV, defaults to MMKVLogLevel.LevelInfo
44
* @return The root folder of MMKV
45
*/
46
public static String initialize(Context context, MMKVLogLevel logLevel);
47
```
48
49
**Usage Example:**
50
51
```java
52
import com.tencent.mmkv.MMKV;
53
import com.tencent.mmkv.MMKVLogLevel;
54
55
// Initialize with debug logging for development
56
MMKV.initialize(this, MMKVLogLevel.LevelDebug);
57
58
// Initialize with error-only logging for production
59
MMKV.initialize(this, MMKVLogLevel.LevelError);
60
```
61
62
### Initialization with Custom Root Directory
63
64
Initialize MMKV with a custom root directory for storing data files.
65
66
```java { .api }
67
/**
68
* Initialize MMKV with customize root folder.
69
* @param context The Android app context
70
* @param rootDir The root folder of MMKV, defaults to $(FilesDir)/mmkv
71
* @return The root folder of MMKV
72
*/
73
public static String initialize(Context context, String rootDir);
74
75
/**
76
* Initialize MMKV with customize root folder and log level.
77
* @param context The Android app context
78
* @param rootDir The root folder of MMKV
79
* @param logLevel The log level of MMKV
80
* @return The root folder of MMKV
81
*/
82
public static String initialize(Context context, String rootDir, MMKVLogLevel logLevel);
83
```
84
85
**Usage Example:**
86
87
```java
88
// Use custom directory on external storage
89
File customDir = new File(getExternalFilesDir(null), "custom_mmkv");
90
MMKV.initialize(this, customDir.getAbsolutePath());
91
92
// With custom log level
93
MMKV.initialize(this, customDir.getAbsolutePath(), MMKVLogLevel.LevelWarning);
94
```
95
96
### Initialization with Library Loader
97
98
Initialize MMKV with a third-party library loader such as ReLinker for improved native library loading reliability.
99
100
```java { .api }
101
/**
102
* Initialize MMKV with a 3rd library loader.
103
* @param context The Android app context
104
* @param loader The 3rd library loader (e.g., ReLinker)
105
* @return The root folder of MMKV
106
*/
107
public static String initialize(Context context, LibLoader loader);
108
109
/**
110
* Initialize MMKV with a 3rd library loader and customize log level.
111
* @param context The Android app context
112
* @param loader The 3rd library loader
113
* @param logLevel The log level of MMKV
114
* @return The root folder of MMKV
115
*/
116
public static String initialize(Context context, LibLoader loader, MMKVLogLevel logLevel);
117
118
/**
119
* Initialize MMKV with customize root folder and a 3rd library loader.
120
* @param context The Android app context
121
* @param rootDir The root folder of MMKV
122
* @param loader The 3rd library loader
123
* @return The root folder of MMKV
124
*/
125
public static String initialize(Context context, String rootDir, LibLoader loader);
126
```
127
128
**Usage Example:**
129
130
```java
131
import com.getkeepsafe.relinker.ReLinker;
132
import com.tencent.mmkv.MMKV;
133
134
// Create a ReLinker-based loader for better reliability
135
MMKV.LibLoader reLinkerLoader = new MMKV.LibLoader() {
136
@Override
137
public void loadLibrary(String libName) {
138
ReLinker.loadLibrary(MyApplication.this, libName);
139
}
140
};
141
142
// Initialize with ReLinker
143
MMKV.initialize(this, reLinkerLoader);
144
```
145
146
### Full Initialization
147
148
Complete initialization with all customization options including error handlers.
149
150
```java { .api }
151
/**
152
* Initialize MMKV with all customize settings.
153
* @param context The Android app context
154
* @param rootDir The root folder of MMKV
155
* @param loader The 3rd library loader
156
* @param logLevel The log level of MMKV
157
* @param handler The error and log handler
158
* @return The root folder of MMKV
159
*/
160
public static String initialize(Context context, String rootDir, LibLoader loader,
161
MMKVLogLevel logLevel, MMKVHandler handler);
162
```
163
164
**Usage Example:**
165
166
```java
167
import com.tencent.mmkv.*;
168
169
MMKVHandler handler = new MMKVHandler() {
170
@Override
171
public MMKVRecoverStrategic onMMKVCRCCheckFail(String mmapID) {
172
Log.e("MMKV", "CRC check failed for " + mmapID);
173
return MMKVRecoverStrategic.OnErrorRecover; // Try to recover data
174
}
175
176
@Override
177
public MMKVRecoverStrategic onMMKVFileLengthError(String mmapID) {
178
Log.e("MMKV", "File length error for " + mmapID);
179
return MMKVRecoverStrategic.OnErrorDiscard; // Discard corrupted data
180
}
181
182
@Override
183
public boolean wantLogRedirecting() {
184
return true; // Redirect MMKV logs to this handler
185
}
186
187
@Override
188
public void mmkvLog(MMKVLogLevel level, String file, int line, String function, String message) {
189
Log.d("MMKV", String.format("[%s:%d] %s - %s", file, line, function, message));
190
}
191
};
192
193
// Full initialization
194
MMKV.initialize(this, customRootDir, reLinkerLoader, MMKVLogLevel.LevelInfo, handler);
195
```
196
197
### Global Configuration
198
199
Methods for managing global MMKV settings after initialization.
200
201
```java { .api }
202
/**
203
* Get the root folder of MMKV.
204
* @return The root folder path
205
*/
206
public static String getRootDir();
207
208
/**
209
* Set the log level of MMKV.
210
* @param level The new log level
211
*/
212
public static void setLogLevel(MMKVLogLevel level);
213
214
/**
215
* Get the device's memory page size.
216
* @return The page size in bytes
217
*/
218
public static native int pageSize();
219
220
/**
221
* Get the version of MMKV.
222
* @return The version string
223
*/
224
public static native String version();
225
226
/**
227
* Notify MMKV that App is about to exit.
228
* Optional - helps with cleanup but not required.
229
*/
230
public static native void onExit();
231
```
232
233
**Usage Example:**
234
235
```java
236
// Get configuration info
237
String rootDir = MMKV.getRootDir();
238
int pageSize = MMKV.pageSize();
239
String version = MMKV.version();
240
241
// Change log level at runtime
242
MMKV.setLogLevel(MMKVLogLevel.LevelError);
243
244
// Optional cleanup on app exit
245
@Override
246
protected void onDestroy() {
247
super.onDestroy();
248
MMKV.onExit();
249
}
250
```
251
252
### Process Mode Validation
253
254
Methods for controlling process mode validation to prevent incorrect usage patterns.
255
256
```java { .api }
257
/**
258
* Manually enable the process mode checker.
259
* Automatically enabled in DEBUG build, disabled in RELEASE build.
260
*/
261
public static void enableProcessModeChecker();
262
263
/**
264
* Manually disable the process mode checker.
265
* When enabled, MMKV throws exceptions for process mode mismatches.
266
*/
267
public static void disableProcessModeChecker();
268
```
269
270
**Usage Example:**
271
272
```java
273
if (BuildConfig.DEBUG) {
274
// Enable strict checking in debug builds
275
MMKV.enableProcessModeChecker();
276
} else {
277
// Disable checking in release for performance
278
MMKV.disableProcessModeChecker();
279
}
280
```
281
282
### Handler Registration (Legacy)
283
284
Legacy methods for registering MMKV handlers. Use the initialize() method with MMKVHandler parameter instead.
285
286
```java { .api }
287
/**
288
* Register a handler for MMKV log redirecting and error handling.
289
* @deprecated Use initialize() with MMKVHandler parameter instead
290
* @param handler The error and log handler
291
*/
292
@Deprecated
293
public static void registerHandler(MMKVHandler handler);
294
295
/**
296
* Unregister the current MMKV handler.
297
*/
298
public static void unregisterHandler();
299
```
300
301
**Usage Example:**
302
303
```java
304
// Legacy handler registration (deprecated)
305
MMKVHandler legacyHandler = new MMKVHandler() {
306
@Override
307
public MMKVRecoverStrategic onMMKVCRCCheckFail(String mmapID) {
308
Log.w("MMKV", "CRC check failed for " + mmapID);
309
return MMKVRecoverStrategic.OnErrorRecover;
310
}
311
312
@Override
313
public MMKVRecoverStrategic onMMKVFileLengthError(String mmapID) {
314
Log.w("MMKV", "File length error for " + mmapID);
315
return MMKVRecoverStrategic.OnErrorDiscard;
316
}
317
318
@Override
319
public boolean wantLogRedirecting() {
320
return true;
321
}
322
323
@Override
324
public void mmkvLog(MMKVLogLevel level, String file, int line, String function, String message) {
325
Log.d("MMKV", String.format("[%s:%d] %s", file, line, message));
326
}
327
};
328
329
// Register handler (deprecated approach)
330
MMKV.registerHandler(legacyHandler);
331
332
// Later, unregister
333
MMKV.unregisterHandler();
334
335
// Preferred approach: use initialize() with handler parameter
336
MMKV.initialize(context, rootDir, loader, logLevel, legacyHandler);
337
```
338
339
## Types
340
341
```java { .api }
342
public interface LibLoader {
343
/**
344
* Load a native library by name
345
* @param libName The name of the library to load
346
*/
347
void loadLibrary(String libName);
348
}
349
350
public enum MMKVLogLevel {
351
LevelDebug, // Debug level (not available for release/production build)
352
LevelInfo, // Info level (default)
353
LevelWarning, // Warning level
354
LevelError, // Error level
355
LevelNone // Disable all logging (not recommended)
356
}
357
358
public interface MMKVHandler {
359
MMKVRecoverStrategic onMMKVCRCCheckFail(String mmapID);
360
MMKVRecoverStrategic onMMKVFileLengthError(String mmapID);
361
boolean wantLogRedirecting();
362
void mmkvLog(MMKVLogLevel level, String file, int line, String function, String message);
363
}
364
365
public enum MMKVRecoverStrategic {
366
OnErrorDiscard, // Discard everything on errors (default)
367
OnErrorRecover // Try to recover as much data as possible
368
}
369
```