Package 

Class MMKV

  • All Implemented Interfaces:
    android.content.SharedPreferences , android.content.SharedPreferences.Editor

    
    public class MMKV
     implements SharedPreferences, SharedPreferences.Editor
                        

    An highly efficient, reliable, multi-process key-value storage framework. THE PERFECT drop-in replacement for SharedPreferences and MultiProcessSharedPreferences.

    • Method Detail

      • initialize

         static String initialize(@NonNull() Context context)

        Initialize MMKV with default configuration.You must call one of the initialize() methods on App startup process before using MMKV.

        Parameters:
        context - The context of Android App, usually from Application.
      • initialize

         static String initialize(@NonNull() Context context, MMKVLogLevel logLevel)

        Initialize MMKV with customize log level.You must call one of the initialize() methods on App startup process before using MMKV.

        Parameters:
        context - The context of Android App, usually from Application.
        logLevel - The log level of MMKV, defaults to LevelInfo.
      • initialize

         static String initialize(@NonNull() Context context, MMKV.LibLoader loader)

        Initialize MMKV with a 3rd library loader.You must call one of the initialize() methods on App startup process before using MMKV.

        Parameters:
        context - The context of Android App, usually from Application.
        loader - The 3rd library loader (for example, the ReLinker .
      • initialize

         static String initialize(@NonNull() Context context, MMKV.LibLoader loader, MMKVLogLevel logLevel)

        Initialize MMKV with a 3rd library loader, and customize log level.You must call one of the initialize() methods on App startup process before using MMKV.

        Parameters:
        context - The context of Android App, usually from Application.
        loader - The 3rd library loader (for example, the ReLinker .
        logLevel - The log level of MMKV, defaults to LevelInfo.
      • initialize

         static String initialize(Context context, String rootDir)

        Initialize MMKV with customize root folder.You must call one of the initialize() methods on App startup process before using MMKV.

        Parameters:
        context - The context of Android App, usually from Application.
        rootDir - The root folder of MMKV, defaults to $(FilesDir)/mmkv.
      • initialize

         static String initialize(Context context, String rootDir, MMKVLogLevel logLevel)

        Initialize MMKV with customize root folder, and log level.You must call one of the initialize() methods on App startup process before using MMKV.

        Parameters:
        context - The context of Android App, usually from Application.
        rootDir - The root folder of MMKV, defaults to $(FilesDir)/mmkv.
        logLevel - The log level of MMKV, defaults to LevelInfo.
      • initialize

         static String initialize(Context context, String rootDir, MMKV.LibLoader loader)

        Initialize MMKV with customize root folder, and a 3rd library loader.You must call one of the initialize() methods on App startup process before using MMKV.

        Parameters:
        context - The context of Android App, usually from Application.
        rootDir - The root folder of MMKV, defaults to $(FilesDir)/mmkv.
        loader - The 3rd library loader (for example, the ReLinker .
      • initialize

         static String initialize(Context context, String rootDir, MMKV.LibLoader loader, MMKVLogLevel logLevel)

        Initialize MMKV with customize settings.You must call one of the initialize() methods on App startup process before using MMKV.

        Parameters:
        context - The context of Android App, usually from Application.
        rootDir - The root folder of MMKV, defaults to $(FilesDir)/mmkv.
        loader - The 3rd library loader (for example, the ReLinker .
        logLevel - The log level of MMKV, defaults to LevelInfo.
      • setLogLevel

         static void setLogLevel(MMKVLogLevel level)

        Set the log level of MMKV.

        Parameters:
        level - Defaults to LevelInfo.
      • onExit

         static native void onExit()

        Notify MMKV that App is about to exit. It's totally fine not calling it at all.

      • mmkvWithID

        @NonNull() static MMKV mmkvWithID(String mmapID)

        Create an MMKV instance with an unique ID (in single-process mode).

        Parameters:
        mmapID - The unique ID of the MMKV instance.
      • mmkvWithID

        @NonNull() static MMKV mmkvWithID(String mmapID, int mode)

        Create an MMKV instance in single-process or multi-process mode.

        Parameters:
        mmapID - The unique ID of the MMKV instance.
        mode - The process mode of the MMKV instance, defaults to SINGLE_PROCESS_MODE.
      • mmkvWithID

        @NonNull() static MMKV mmkvWithID(String mmapID, int mode, long expectedCapacity)

        Create an MMKV instance in single-process or multi-process mode.

        Parameters:
        mmapID - The unique ID of the MMKV instance.
        mode - The process mode of the MMKV instance, defaults to SINGLE_PROCESS_MODE.
        expectedCapacity - The file size you expected when opening or creating file
      • mmkvWithID

        @NonNull() static MMKV mmkvWithID(String mmapID, int mode, @Nullable() String cryptKey)

        Create an MMKV instance in customize process mode, with an encryption key.

        Parameters:
        mmapID - The unique ID of the MMKV instance.
        mode - The process mode of the MMKV instance, defaults to SINGLE_PROCESS_MODE.
        cryptKey - The encryption key of the MMKV instance (no more than 16 bytes).
      • mmkvWithID

        @NonNull() static MMKV mmkvWithID(String mmapID, String rootPath)

        Create an MMKV instance in customize folder.

        Parameters:
        mmapID - The unique ID of the MMKV instance.
        rootPath - The folder of the MMKV instance, defaults to $(FilesDir)/mmkv.
      • mmkvWithID

        @NonNull() static MMKV mmkvWithID(String mmapID, String rootPath, long expectedCapacity)

        Create an MMKV instance in customize folder.

        Parameters:
        mmapID - The unique ID of the MMKV instance.
        rootPath - The folder of the MMKV instance, defaults to $(FilesDir)/mmkv.
        expectedCapacity - The file size you expected when opening or creating file
      • mmkvWithID

        @NonNull() static MMKV mmkvWithID(String mmapID, int mode, @Nullable() String cryptKey, String rootPath, long expectedCapacity)

        Create an MMKV instance with customize settings all in one.

        Parameters:
        mmapID - The unique ID of the MMKV instance.
        mode - The process mode of the MMKV instance, defaults to SINGLE_PROCESS_MODE.
        cryptKey - The encryption key of the MMKV instance (no more than 16 bytes).
        rootPath - The folder of the MMKV instance, defaults to $(FilesDir)/mmkv.
        expectedCapacity - The file size you expected when opening or creating file
      • mmkvWithID

        @NonNull() static MMKV mmkvWithID(String mmapID, int mode, @Nullable() String cryptKey, String rootPath)

        Create an MMKV instance with customize settings all in one.

        Parameters:
        mmapID - The unique ID of the MMKV instance.
        mode - The process mode of the MMKV instance, defaults to SINGLE_PROCESS_MODE.
        cryptKey - The encryption key of the MMKV instance (no more than 16 bytes).
        rootPath - The folder of the MMKV instance, defaults to $(FilesDir)/mmkv.
      • backedUpMMKVWithID

        @NonNull() static MMKV backedUpMMKVWithID(String mmapID, int mode, @Nullable() String cryptKey, String rootPath)

        Get an backed-up MMKV instance with customize settings all in one.

        Parameters:
        mmapID - The unique ID of the MMKV instance.
        mode - The process mode of the MMKV instance, defaults to SINGLE_PROCESS_MODE.
        cryptKey - The encryption key of the MMKV instance (no more than 16 bytes).
        rootPath - The backup folder of the MMKV instance.
      • mmkvWithAshmemID

        @NonNull() static MMKV mmkvWithAshmemID(Context context, String mmapID, int size, int mode, @Nullable() String cryptKey)

        Create an MMKV instance base on Anonymous Shared Memory, aka not synced to any disk files.

        Parameters:
        context - The context of Android App, usually from Application.
        mmapID - The unique ID of the MMKV instance.
        size - The maximum size of the underlying Anonymous Shared Memory.Anonymous Shared Memory on Android can't grow dynamically, must set an appropriate size on creation.
        mode - The process mode of the MMKV instance, defaults to SINGLE_PROCESS_MODE.
        cryptKey - The encryption key of the MMKV instance (no more than 16 bytes).
      • defaultMMKV

        @NonNull() static MMKV defaultMMKV(int mode, @Nullable() String cryptKey)

        Create the default MMKV instance in customize process mode, with an encryption key.

        Parameters:
        mode - The process mode of the MMKV instance, defaults to SINGLE_PROCESS_MODE.
        cryptKey - The encryption key of the MMKV instance (no more than 16 bytes).
      • enableProcessModeChecker

         static void enableProcessModeChecker()

        Manually enable the process mode checker.By default, it's automatically enabled in DEBUG build, and disabled in RELEASE build.If it's enabled, MMKV will throw exceptions when an MMKV instance is created with mismatch process mode.

      • disableProcessModeChecker

         static void disableProcessModeChecker()

        Manually disable the process mode checker.By default, it's automatically enabled in DEBUG build, and disabled in RELEASE build.If it's enabled, MMKV will throw exceptions when an MMKV instance is created with mismatch process mode.

      • reKey

         native boolean reKey(@Nullable() String cryptKey)

        Transform plain text into encrypted text, or vice versa by passing a null encryption key.You can also change existing crypt key with a different cryptKey.

        Parameters:
        cryptKey - The new encryption key (no more than 16 bytes).
      • checkReSetCryptKey

         native void checkReSetCryptKey(@Nullable() String cryptKey)

        Just reset the encryption key (will not encrypt or decrypt anything).Usually you should call this method after another process has reKey the multi-process MMKV instance.

        Parameters:
        cryptKey - The new encryption key (no more than 16 bytes).
      • lock

         native void lock()

        Exclusively inter-process lock the MMKV instance.It will block and wait until it successfully locks the file.It will make no effect if the MMKV instance is created with SINGLE_PROCESS_MODE.

      • unlock

         native void unlock()

        Exclusively inter-process unlock the MMKV instance.It will make no effect if the MMKV instance is created with SINGLE_PROCESS_MODE.

      • tryLock

         native boolean tryLock()

        Try exclusively inter-process lock the MMKV instance.It will not block if the file has already been locked by another process.It will make no effect if the MMKV instance is created with SINGLE_PROCESS_MODE.

      • encode

         boolean encode(String key, boolean value, int expireDurationInSecond)

        Set value with customize expiration in seconds.

        Parameters:
        expireDurationInSecond - override the default duration, ExpireNever (0) means never expire.
      • encode

         boolean encode(String key, int value, int expireDurationInSecond)

        Set value with customize expiration in seconds.

        Parameters:
        expireDurationInSecond - override the default duration, ExpireNever (0) means never expire.
      • encode

         boolean encode(String key, long value, int expireDurationInSecond)

        Set value with customize expiration in seconds.

        Parameters:
        expireDurationInSecond - override the default duration, ExpireNever (0) means never expire.
      • encode

         boolean encode(String key, float value, int expireDurationInSecond)

        Set value with customize expiration in seconds.

        Parameters:
        expireDurationInSecond - override the default duration, ExpireNever (0) means never expire.
      • encode

         boolean encode(String key, double value, int expireDurationInSecond)

        Set value with customize expiration in seconds.

        Parameters:
        expireDurationInSecond - override the default duration, ExpireNever (0) means never expire.
      • encode

         boolean encode(String key, @Nullable() String value, int expireDurationInSecond)

        Set value with customize expiration in seconds.

        Parameters:
        expireDurationInSecond - override the default duration, ExpireNever (0) means never expire.
      • encode

         boolean encode(String key, @Nullable() Set<String> value, int expireDurationInSecond)

        Set value with customize expiration in seconds.

        Parameters:
        expireDurationInSecond - override the default duration, ExpireNever (0) means never expire.
      • encode

         boolean encode(String key, @Nullable() Array<byte> value, int expireDurationInSecond)

        Set value with customize expiration in seconds.

        Parameters:
        expireDurationInSecond - override the default duration, ExpireNever (0) means never expire.
      • encode

         boolean encode(String key, @Nullable() Parcelable value, int expireDurationInSecond)

        Set value with customize expiration in seconds.

        Parameters:
        expireDurationInSecond - override the default duration, ExpireNever (0) means never expire.
      • getValueSize

         int getValueSize(String key)

        Get the actual size consumption of the key's value.Note: might be a little bigger than value's length.

        Parameters:
        key - The key of the value.
      • getValueActualSize

         int getValueActualSize(String key)

        Get the actual size of the key's value. String's length or byte[]'s length, etc.

        Parameters:
        key - The key of the value.
      • containsKey

         boolean containsKey(String key)

        Check whether or not MMKV contains the key.

        Parameters:
        key - The key of the value.
      • totalSize

         long totalSize()

        Get the size of the underlying file. Align to the disk block size, typically 4K for an Android device.

      • actualSize

         long actualSize()

        Get the actual used size of the MMKV instance.This size might increase and decrease as MMKV doing insertion and full write back.

      • removeValuesForKeys

         native void removeValuesForKeys(Array<String> arrKeys)

        Batch remove some keys from the MMKV instance.

        Parameters:
        arrKeys - The keys to be removed.
      • clearAll

         native void clearAll()

        Clear all the key-values inside the MMKV instance.The data file will be trimmed down to `pageSize`, and some sync operations will be calledIf you do not want to trim the file, use clearAllWithKeepingSpace instead for better performance

      • trim

         native void trim()

        The totalSize of an MMKV instance won't reduce after deleting key-values,call this method after lots of deleting if you care about disk usage.Note that clearAll has a similar effect.

      • importFrom

         long importFrom(MMKV src)

        import all key-value items from src

      • close

         native void close()

        Call this method if the MMKV instance is no longer needed in the near future.Any subsequent call to any MMKV instances with the same ID is undefined behavior.

      • clearMemoryCache

         native void clearMemoryCache()

        Clear memory cache of the MMKV instance.You can call it on memory warning.Any subsequent call to the MMKV instance will trigger all key-values loading from the file again.

      • sync

         void sync()

        Save all mmap memory to file synchronously.You don't need to call this, really, I mean it.Unless you worry about the device running out of battery.

      • async

         void async()

        Save all mmap memory to file asynchronously.No need to call this unless you worry about the device running out of battery.

      • isFileValid

         static boolean isFileValid(String mmapID)

        Check whether the MMKV file is valid or not.Note: Don't use this to check the existence of the instance, the result is undefined on nonexistent files.

      • isFileValid

         static native boolean isFileValid(String mmapID, @Nullable() String rootPath)

        Check whether the MMKV file is valid or not on customize folder.

        Parameters:
        mmapID - The unique ID of the MMKV instance.
        rootPath - The folder of the MMKV instance, defaults to $(FilesDir)/mmkv.
      • removeStorage

         static boolean removeStorage(String mmapID)

        remove the storage of the MMKV, including the data file & meta file (.crc)Note: the existing instance (if any) will be closed & destroyed

        Parameters:
        mmapID - The unique ID of the MMKV instance.
      • removeStorage

         static native boolean removeStorage(String mmapID, @Nullable() String rootPath)

        remove the storage of the MMKV, including the data file & meta file (.crc)Note: the existing instance (if any) will be closed & destroyed

        Parameters:
        mmapID - The unique ID of the MMKV instance.
        rootPath - The folder of the MMKV instance, defaults to $(FilesDir)/mmkv.
      • checkExist

         static boolean checkExist(String mmapID)

        check existence of the MMKV file

        Parameters:
        mmapID - The unique ID of the MMKV instance.
      • checkExist

         static native boolean checkExist(String mmapID, @Nullable() String rootPath)

        check existence of the MMKV file

        Parameters:
        mmapID - The unique ID of the MMKV instance.
        rootPath - The folder of the MMKV instance, defaults to $(FilesDir)/mmkv.
      • importFromSharedPreferences

         int importFromSharedPreferences(@NonNull() SharedPreferences preferences)

        Atomically migrate all key-values from an existent SharedPreferences to the MMKV instance.

        Parameters:
        preferences - The SharedPreferences to import from.
      • backupOneToDirectory

         static native boolean backupOneToDirectory(String mmapID, String dstDir, @Nullable() String rootPath)

        backup one MMKV instance to dstDir

        Parameters:
        mmapID - the MMKV ID to backup
        dstDir - the backup destination directory
        rootPath - the customize root path of the MMKV, if null then backup from the root dir of MMKV
      • restoreOneMMKVFromDirectory

         static native boolean restoreOneMMKVFromDirectory(String mmapID, String srcDir, @Nullable() String rootPath)

        restore one MMKV instance from srcDir

        Parameters:
        mmapID - the MMKV ID to restore
        srcDir - the restore source directory
        rootPath - the customize root path of the MMKV, if null then restore to the root dir of MMKV
      • backupAllToDirectory

         static native long backupAllToDirectory(String dstDir)

        backup all MMKV instance from default root dir to dstDir

        Parameters:
        dstDir - the backup destination directory
      • restoreAllFromDirectory

         static native long restoreAllFromDirectory(String srcDir)

        restore all MMKV instance from srcDir to default root dir

        Parameters:
        srcDir - the restore source directory
      • enableAutoKeyExpire

         native boolean enableAutoKeyExpire(int expireDurationInSecond)

        Enable auto key expiration. This is a upgrade operation, the file format will change.And the file won't be accessed correctly by older version (v1.2.16) of MMKV.NOTICE: enableCompareBeforeSet will be invalid when Expiration is on

        Parameters:
        expireDurationInSecond - the expire duration for all keys, ExpireNever (0) means no default duration (aka each key will have it's own expire date)
      • disableAutoKeyExpire

         native boolean disableAutoKeyExpire()

        Disable auto key expiration. This is a downgrade operation.

      • enableCompareBeforeSet

         void enableCompareBeforeSet()

        Enable data compare before set, for better performance.If data for key seldom changes, use it.When encryption or expiration is on, compare-before-set will be invalid.For encryption, compare operation must decrypt data which is time consuming.For expiration, compare is useless because in most cases the expiration time changes every time.

      • getAll

         Map<String, out Object> getAll()

        Intentionally Not Supported. Because MMKV does type-eraser inside to get better performance.

      • mmkvWithAshmemFD

        @NonNull()@Contract(value = _, _, _, _ -> new) static MMKV mmkvWithAshmemFD(String mmapID, int fd, int metaFD, String cryptKey)

        Get an ashmem MMKV instance that has been initiated by another process.Normally you should just call mmkvWithAshmemID instead.

        Parameters:
        mmapID - The unique ID of the MMKV instance.
        fd - The file descriptor of the ashmem of the MMKV file, transferred from another process by binder.
        metaFD - The file descriptor of the ashmem of the MMKV crc file, transferred from another process by binder.
        cryptKey - The encryption key of the MMKV instance (no more than 16 bytes).
      • createNativeBuffer

        @Nullable() static NativeBuffer createNativeBuffer(int size)

        Create an native buffer, whose underlying memory can be directly transferred to another JNI method.Avoiding unnecessary JNI boxing and unboxing.An NativeBuffer must be manually destroyNativeBuffer to avoid memory leak.

        Parameters:
        size - The size of the underlying memory.
      • registerHandler

         static void registerHandler(MMKVHandler handler)

        Register a handler for MMKV log redirecting, and error handling.

      • isMultiProcess

         native boolean isMultiProcess()

        Check if this instance is in multi-process mode.

      • isReadOnly

         native boolean isReadOnly()

        Check if this instance is in read-only mode.