kotlin,jetpack compose,使用DataStore保存数据,让程序下次启动时自动获取

复制代码
implementation ("androidx.datastore:datastore-preferences:1.0.0")
复制代码
package com.example.mydatastore

import android.content.Context
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.TextField
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.example.mydatastore.ui.theme.MyDataStoreTheme
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

// MainActivity 是应用的入口 Activity,继承自 ComponentActivity
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 启用边缘到边缘的显示模式
        enableEdgeToEdge()
        // 设置 Compose 内容
        setContent {
            MyDataStoreTheme {
                // 显示 NumberInputScreen 组件
                NumberInputScreen()
            }
        }
    }
}

// 定义 DataStore 的扩展属性,用于访问应用的设置数据存储
val Context.settingsDataStore: DataStore<Preferences> by preferencesDataStore(name = "my_settings")

// NumberInputScreen 是一个可组合函数,用于显示数字输入界面
@Composable
fun NumberInputScreen() {
    // 获取当前上下文
    val context = LocalContext.current
    // 使用 remember 和 mutableStateOf 来保存输入的数字
    var number by remember { mutableStateOf(0) }

    // 使用 LaunchedEffect 在组合时执行一次,从 DataStore 读取初始值
    LaunchedEffect(Unit) {
        context.settingsDataStore.data.collect { preferences ->
            number = preferences[PreferencesKeys.NUMBER] ?: 0
        }
    }

    // 显示一个 TextField,用于输入数字
    TextField(
        value = number.toString(),
        onValueChange = { newValue ->
            // 将输入的值转换为整数,如果转换成功则更新状态并保存到 DataStore
            newValue.toIntOrNull()?.let { num ->
                number = num
                // 在 IO 线程中异步保存到 DataStore
                CoroutineScope(Dispatchers.IO).launch {
                    context.settingsDataStore.edit { settings ->
                        settings[PreferencesKeys.NUMBER] = num
                    }
                }
            }
        },
        // 设置键盘类型为数字键盘
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
    )
}

// PreferencesKeys 是一个单例对象,用于定义 DataStore 的键
private object PreferencesKeys {
    val NUMBER = intPreferencesKey("saved_number")
}
相关推荐
Digitally25 分钟前
如何从 Android 设备打印短信(5 种方法)
android
casual_clover33 分钟前
Android 中 打开文件选择器(ACTION_OPEN_DOCUMENT )
android
_龙小鱼_2 小时前
卡顿检测与 Choreographer 原理
android·kotlin
云手机管家3 小时前
账号风控突破:云手机设备指纹篡改检测与反制技术解析
android·运维·网络协议·网络安全·智能手机·矩阵·自动化
千里马-horse3 小时前
Detected for tasks ‘compileDebugJavaWithJavac‘ (17) and ‘kspDebugKotlin‘ (21).
android·jdk·kspdebugkotlin
柯南二号5 小时前
【Android】Android 实现一个依赖注入的注解
android
archko7 小时前
语音识别-3,添加ai问答
android·人工智能
奔跑吧 android13 小时前
【android bluetooth 案例分析 03】【PTS 测试 】【PBAP/PCE/SGSIT/SERR/BV-01-C】
android·pts·aosp·pbap·sgsit
難釋懷16 小时前
Android开发-Application
android
seven272917 小时前
Android 适配之——targetSdkVersion 30升级到31-34需要注意些什么?
android·版本设置31-34·targetsdk