Android: MMKV - key-value store

Table of contents

1. Introduction to MMKV

1. Features and advantages:

 2.Usage Guide:

 3. Dependency packages:

2. Commonly used methods of MMKV

1. Initialize and obtain instances:

2. Store data:

 3. Read data

4. Delete data

 5. Other operations:

3. Examples of using MMKV

 MainActivity:

 activity_main:

operation result:

4. Comparison between MMKV and SharedPreferences

1. Introduction to MMKV

        MMKV is a lightweight key-value store for the Android platform that provides an efficient and reliable way to store and read data in applications.

1. Features and advantages:

  • High performance: Compared with traditional storage methods such as SharedPreferences and SQLite, MMKV performs well in terms of performance.
  • Lightweight: MMKV is a small library with no external dependencies and easy to integrate into existing projects.
  • Multi-threading support: MMKV has good multi-threading support and can safely perform data reading and writing operations in concurrent scenarios.
  • Ease of use: MMKV provides a simple and easy-to-use API that supports storage and reading operations of various data types.
  • Data security: MMKV uses a built-in AES encryption mechanism to protect the security of stored data.

 2.Usage Guide:

  1. Introduce dependencies: Add MMKV dependencies in the project's build.gradle file.
  2. Initialize MMKV: Initialize the MMKV instance at the entrance of the application, and set parameters such as storage path and encryption key.
  3. Store data: Use the putXXX() method to store data into MMKV, supporting various data types.
  4. Read data: Use the getXXX() method to read data from MMKV and perform corresponding type conversion.
  5. Other operations: MMKV also provides operations such as deleting specific key values ​​and clearing all data.

 3. Dependency packages:

​dependencies {
   implementation 'com.tencent:mmkv:1.2.10'

}

2. Commonly used methods of MMKV

1. Initialize and obtain instances:

String rootDir = MMKV.initialize(context); // 初始化默认根目录
MMKV mmkv = MMKV.defaultMMKV(); // 获取默认的MMKV实例

2. Store data:

mmkv.encode("key", value); // 存储数据,自动根据类型选择合适的方法
// 或者使用特定类型的存储方法
mmkv.putInt("intKey", intValue);
mmkv.putLong("longKey", longValue);
mmkv.putFloat("floatKey", floatValue);
mmkv.putBoolean("booleanKey", booleanValue);
mmkv.putString("stringKey", stringValue);
mmkv.putStringSet("setKey", stringSet);

 3. Read data

Object value = mmkv.decode("key"); // 读取数据,自动根据类型选择合适的方法
// 或者使用特定类型的读取方法
int intValue = mmkv.getInt("intKey", defaultValue);
long longValue = mmkv.getLong("longKey", defaultValue);
float floatValue = mmkv.getFloat("floatKey", defaultValue);
boolean booleanValue = mmkv.getBoolean("booleanKey", defaultValue);
String stringValue = mmkv.getString("stringKey", defaultValue);
Set<String> stringSet = mmkv.getStringSet("setKey", defaultSet);

4. Delete data

mmkv.remove("key"); // 删除指定键值对
mmkv.removeValueForKey("key"); // 同上,作用相同
mmkv.removeValuesForKeys(new String[]{"key1", "key2"}); // 删除多个键值对
mmkv.clearAll(); // 清空所有数据

 5. Other operations:

boolean contains = mmkv.containsKey("key"); // 判断是否包含指定的键
int count = mmkv.count(); // 获取存储的数据总数
String[] allKeys = mmkv.allKeys(); // 获取所有存储的键

3. Examples of using MMKV

 MainActivity:

package com.example.mmkvdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import com.tencent.mmkv.MMKV;


public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
    EditText password, account;
    Button login, register;
    CheckBox mCheckBox;
    String Password, Account;
    MMKV mmkv;
    String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        // 初始化MMKV
        String rootDir = MMKV.initialize(this);
        Log.d(TAG, "路径:" + rootDir);

        // 读取保存的账号和密码
        mmkv = MMKV.defaultMMKV();
        if (mmkv.contains("account") && mmkv.contains("password")) {
            Account = mmkv.decodeString("account", "");
            Password = mmkv.decodeString("password", "");
            account.setText(Account);
            password.setText(Password);
        }
    }

    private void initView() {
        mCheckBox = findViewById(R.id.Login_Remember);
        login = findViewById(R.id.login_btn_login);
        register = findViewById(R.id.login_btn_register);
        password = findViewById(R.id.login_edit_pwd);
        account = findViewById(R.id.login_edit_account);
        mCheckBox.setOnCheckedChangeListener(this);
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "点击了注册", Toast.LENGTH_LONG).show();
            }
        });
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "点击了登录", Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            if (!TextUtils.isEmpty(password.getText().toString()) && !TextUtils.isEmpty(account.getText().toString())) {
                // 存储数据
                Account = account.getText().toString();
                Password = password.getText().toString();
                mmkv.putString("account", Account); // 存储数据
                mmkv.putString("password", Password);
            }
        } else {
            // 清除保存的账号和密码
            mmkv.removeValuesForKeys(new String[]{"account", "password"});
        }
    }
}

 activity_main:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
      >

    <RelativeLayout
        android:id="@+id/login_view"
        android:layout_width="400dp"
        android:layout_height="800dp"
        android:layout_centerInParent="true">

        <Button
            android:id="@+id/login_btn_register"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/login_btn_login"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="10dp"
            android:background="#e52525"
            android:text="注册"
            android:textColor="#ffffff"
            android:textSize="20dp" />

        <Button
            android:id="@+id/login_btn_login"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/login_edit_pwd"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="52dp"
            android:background="#545bcb"
            android:text="登录"
            android:textColor="#ffffff"
            android:textSize="20dp" />

        <EditText
            android:id="@+id/login_edit_pwd"
            android:layout_width="400dp"
            android:layout_height="60dp"
            android:layout_below="@+id/login_edit_account"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:ems="10"
            android:hint="请输入您的密码"
            android:inputType="textPassword"
            android:textColor="#ffff00" />

        <EditText
            android:id="@+id/login_edit_account"
            android:layout_width="400dp"
            android:layout_height="60dp"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="20dp"
            android:hint="请输入您的用户名"
            android:inputType="textPersonName"
            android:textColor="#ffff00" />

        <CheckBox
            android:id="@+id/Login_Remember"
            android:layout_width="100dp"
            android:layout_height="20dp"
            android:layout_below="@+id/login_edit_pwd"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:checked="false"
            android:text="记住密码"
            android:textSize="15dp" />

        <TextView
            android:id="@+id/login_text_change_pwd"
            android:layout_width="65dp"
            android:layout_height="20dp"
            android:layout_below="@+id/login_edit_pwd"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:text="忘记密码"
            android:textSize="15dp" />
    </RelativeLayout>
</LinearLayout>

operation result:

 

4. Comparison between MMKV and SharedPreferences

MMKV has the following advantages over SharedPreferences (sp):

1. Better performance: MMKV uses a custom key-value storage engine, and the underlying method uses mmap mapping files, which avoids the overhead of memory copying and serialization/deserialization. In contrast, SharedPreferences is based on XML file storage, and each read and write requires IO operations, resulting in lower performance.

2. Larger storage capacity: MMKV supports storing data in independent files and can set the maximum size of a single file, while SharedPreferences stores data in an XML file. When the amount of data stored is large, the performance will drop.

3. Multi-process concurrent security: MMKV uses the file lock mechanism to achieve concurrent secure access by multiple processes, avoiding data confusion and conflicts. SharedPreferences does not provide security guarantees for multi-process concurrency. When multiple processes operate on the same SharedPreferences file at the same time, data anomalies may occur.

4. Support custom encryption: MMKV supports custom encryptors, which can encrypt and protect stored data to increase data security. SharedPreferences does not directly support encryption and requires developers to manually encrypt the stored data.

5. The API is simpler and easier to use: MMKV provides a simple and easy-to-use API, which is more convenient and faster to use. It can directly store various types of data without manual type conversion. SharedPreferences requires manual type conversion and key-value splicing.

        In general, MMKV has obvious advantages over SharedPreferences in terms of performance, storage capacity, multi-process concurrency security and encryption. It is especially suitable for data storage needs in high-performance requirements, large data storage or multi-process scenarios. .

 

 

Guess you like

Origin blog.csdn.net/A125679880/article/details/132157268