# MMKV **Repository Path**: openharmony-tpc/MMKV ## Basic Information - **Project Name**: MMKV - **Description**: No description available - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 28 - **Forks**: 36 - **Created**: 2022-02-21 - **Last Updated**: 2025-09-04 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## 🚨 **重要提示 | IMPORTANT** > > **⚠️ 此代码仓已归档。新地址请访问 [MMKV](https://gitcode.com/openharmony-tpc/MMKV)。| ⚠️ This repository has been archived. For the new address, please visit [MMKV](https://gitcode.com/openharmony-tpc/MMKV).** > --- > # MMKV ## Deprecated This library is deprecated. You are advised to use [@tencent/mmkv](https://ohpm.openharmony.cn/#/cn/detail/@tencent%2Fmmkv). ## Introduction MMKV is a lightweight key-value storage framework, offering the following features: - Storage of data types such as number, boolean, string, and Set\ - Serialization and deserialization of class objects that inherit **SerializeBase.ets** in components - Data backup - Data recovery ## How to Install ``` ohpm install @ohos/mmkv ``` For details about the OpenHarmony ohpm environment configuration, see [OpenHarmony HAR](https://gitee.com/openharmony-tpc/docs/blob/master/OpenHarmony_har_usage.en.md). ## Changes in API Usage 1. Import **this.context** in [EntryAbility.ts](entry%2Fsrc%2Fmain%2Fets%2Fentryability%2FEntryAbility.ts). ```typescript import { GlobalContext } from '../bean/GlobalContext'; ... GlobalContext.getContext().setObject("filesDir", this.context.filesDir); GlobalContext.getContext().setObject("cacheDir", this.context.cacheDir); GlobalContext.getContext().setObject("context", this.context); ``` 2. Obtain the **context** object through **getObject** when necessary. ```typescript import { GlobalContext } from '@ohos/svg/src/main/ets/components/GlobalContext'; import { Context } from '@ohos.abilityAccessCtrl'; let context = GlobalContext.getContext().getObject("context") as Context prefrence.getPreferences(context, fileName, (error, preferences) => { ... } ``` ## How to Use ### Perform **GlobalContext** operations in **aboutToAppear()**. filePath = GlobalContext.getContext().getObject("filesDir") as string cachePath = GlobalContext.getContext().getObject("cacheDir") as string ### 1. Initialization Initialize MMKV by setting the root directory (**rootPath**) for file storage and the cache directory (**cachePath**). MMKV.initialize(rootPath, cachePath) let context = GlobalContext.getContext().getObject("context") as Context let kv = MMKV.getMMKVWithMMapID('imported', MMKV.SINGLE_PROCESS_MODE, "", undefined); ### 2. Instantiation let mmkv = MMKV.getBackedUpMMKVWithID(mmapID, MMKV.SINGLE_PROCESS_MODE, "Tencent MMKV", backupRootDir); ### 3. Storage and Access of Key-Value Pairs #### 3.1 Common Data Types: boolean, number, string, Set\ ##### Example of Storing Key-Value Pairs mmkv.encodeBool('boolData', false) mmkv.encodeNumber('numberData', 3.0122) mmkv.encodeString('stringData', 'dsfsg') let set1 = new Set() set1.add('ass1') mmkv.encodeSet('setData', set1) ##### Example of Accessing Key-Value Pairs mmkv.decodeBool('boolData') mmkv.decodeNumber('stringData') mmkv.decodeString('numberData') mmkv.decodeSet('setData') #### 3.2 Serialization and Deserialization of Class Objects ##### Requirements Class objects must inherit **SerializeBase**, and serializable properties must be annotated with **@Serialize()**. class MyClass extends SerializeBase{ @Serialize() public code: number = 0; public title: string = 'titles'; @Serialize() public description: string = 'descs'; } ##### Example of Storing Data let myClass1 = new MyClass(1, 't1', 'desc1') kv.encodeSerialize('serialize111', myClass1) ##### Example of Accessing Data let myClass2 = kv.decodeSerialize('serialize111', new MyClass()) ### 4. Migrating System Lightweight Storage Data to MMKV Storage // name indicates the preference file name, and callback indicates the asynchronous callback. preferencesToMMKV(name: string, callback: ICallBack, context: Context) ### 5. Encryption Key Configuration mmkv.reCryptKey('Key_seq_1') // Key_seq_1: encryption key ### 6. Data Backup ##### Backing Up Specific MMKV Data MMKV.backupOneToDirectory(mmapID, backupRootDir, otherDir)// mmapID: ID of the MMKV instance to back up; backupRootDir: destination directory for the backup; otherDir: current directory where the MMKV data is stored ##### Backing Up All MMKV Data MMKV.backupAllToDirectory(backupRootDir) // backupRootDir: destination directory for the backup ### 7. Data Restoration ##### Restoring Specific MMKV Data MMKV.restoreOneMMKVFromDirectory(mmapID, srcDir, otherDir)// mmapID: ID of the MMKV instance to restore; srcDir: source directory; otherDir: destination directory where the MMKV data will be restored ##### Restoring All MMKV Data MMKV.restoreAllFromDirectory(srcDir) // srcDir: destination directory where the MMKV data will be restored ### 8. Clearing All Stored Data mmkv.clearAll() ## Available APIs | API | Parameter | Description | | --------------------------------- | ------------------------------------------------------------ | -------------------------------------- | | version | N/A | Obtains the native version. | | getRootDir | N/A | Obtains the storage path. | | pageSize | N/A | Obtains the number of device memory pages. | | getDefaultMMKV | mode?: number, cryptKey?: string | Obtains the default instance. | | totalSize | N/A | Obtains the size of the base file. | | encode | key: string, value: number, Set\, string, boolean | Stores data. | | decodeString | key: string, defaultValue?: string | Obtains the string value by key. | | decodeBool | key: string, defaultValue?: boolean | Obtains the Boolean value by key. | | decodeNumber | handle: string, key: string, defaultValue: number | Obtains the number value by key. | | decodeSet | key: string, defaultValue?: Set | Obtains the array value by key. | | containsKey | key: string | Checks whether a key is contained. | | getCryptKey | N/A | Obtains the encryption key. | | getMMapID | N/A | Obtains the instance ID. | | removeValueForKey | key: string | Removes a value by key. | | removeValuesForKeys | value: string[] | Removes values in batch. | | clearAll | N/A | Clears all key values. | | count | N/A | Obtains the number of keys. | | isFileValid | mmapID: string | Checks whether the MMKV file is valid. | | reCryptKey | cryptKey: string | Changes the encryption key. | | backupOneToDirectory | mmapID: string, dstDir: string, rootPath: string | Backs up an MMKV instance to the specified destination directory. | | backupAllToDirectory | dstDir: string | Backs up all MMKV instances to the specified destination directory. | | restoreOneMMKVFromDirectory | mmapID: string, srcDir: string, rootPath: string | Restores an MMKV instance from the specified source directory. | | restoreAllFromDirectory | srcDir: string | Restores all MMKV instances from the specified source directory. | | initialize | root: string, cachePath: string, logLevel?: MMKVLogLevel | Initializes MMKV. | | getBackedUpMMKVWithID | mmapID: string, mode: number, crpKey: string, rootPath: string | Obtains a backed-up MMKV instance | | encodeSerialize | key: string, value: SerializeBase | Stores serialized data. | | decodeSerialize | key: string, defaultValue: T | Obtains serialized data by key. | | encodeString | key: string, value: string | Stores string data. | | encodeSet | key: string, value: Set\ | Store Set data | | encodeBool | key: string, value: boolean | Stores Boolean data. | | encodeNumber | key: string, value: number | Stores number data. | | getAllKeys | N/A | Obtains all keys. | | clearMemoryCache | N/A | Clears the memory cache of this MMKV instance. | | actualSize | N/A | Obtains the actual size used by this MMKV instance. | | getHandle | N/A | Obtains the handle of this MMKV instance. | | close | N/A | Closes this MMKV instance. | | trim | N/A | Trims this MMKV instance by clearing all key values in the MMKV instance. | | checkContentChangedByOuterProcess | N/A | Manually checks for inter-process content changes. | | setLogLevel | level: MMKVLogLevel | Sets the log level. | | checkReSetCryptKey | cryptKey: string | Changes the encryption key (which does not encrypt or decrypt any content).| | simpleLog | level: MMKVLogLevel, message: string | Prints logs. | | preferencesToMMKV | context: Context, name: string, callback: ICallBack | Migrates system lightweight storage data to MMKV storage. | | LogUtil.d | message: string | Prints debug logs. | | LogUtil.i | message: string | Prints info logs. | | LogUtil_e | message: string | Prints error logs. | | isEnd | N/A | Checks whether file reading has ended. | | close | N/A | Closes file reading. | For details about unit test cases, see [TEST.md](https://gitee.com/openharmony-tpc/MMKV/blob/master/TEST.md). ## Constraints This project has been verified in the following versions: - DevEco Studio: 4.0 (4.0.3.513), SDK: API 10 (4.0.10.10) - DevEco Studio: 4.0 Canary2 (4.0.3.312), SDK: API 10 (4.0.9.3) - DevEco Studio: 3.1 Beta2 (3.1.0.400), SDK: API 9 Release (3.2.11.9) ## Directory Structure ``` |----MMMKV | |---- entry # Sample code | |---- library # MMMKV library | |---- index.ets # External APIs | |---- README.md # Readme ``` ## How to Contribute If you find any problem during the use, submit an [Issue](https://gitee.com/openharmony-tpc/MMKV/issues) or a [PR](https://gitee.com/openharmony-tpc/MMKV/pulls) to us. ## License This project is licensed under [BSD 3-Clause License](https://www.tizen.org/bsd-3-clause-license).