Android DataStore使用实例

Jetpack DataStore 是一种数据存储解决方案,允许您使用协议缓冲区存储键值对或类型化对象。DataStore 使用 Kotlin 协程和 Flow 以异步、一致的事务方式存储数据。

如果您当前在使用 SharedPreferences 存储数据,请考虑迁移到 DataStore。

这是官方文档的前言,下面我们用一个简单的实例来达到学习的目的
新建立一个基于空activity的安卓工程,组件界面如下:


image.png

这个datastore是架构组件之一,为了使用它你必须引入其它架构组件

buildscript {
    ext{
        data_store_version = '1.0.0'
        coroutines_android_version = '1.5.1-native-mt'
        lifecycle_extensions_version = '2.2.0'
        lifecycle_version = '2.3.1'
    }
   ...
}

dependencies {

    //Coroutine support
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_android_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_android_version"
    /////
    // ViewModel and LiveData
    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_extensions_version"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
    /////
    //Datastore Preferences
    implementation "androidx.datastore:datastore-preferences:$data_store_version"
    /////
...
}

下面是activity的所有代码, 看看就明白了,然后看官方文档就行,主要是得明白得引入其它架构组件
但要注意以下容易犯错的点:
/**
* 我们通过验证发现,存储dataStore的代码不能在onStop和onDestroy执行
* 而onPause则是可以的,一般是用户退出程序存储下数据是合理的,但如果在onPause存储也不是一个坏事
* 毕竟我们用这个存储的数据往往都是简单的配置数据,很多时候仅仅是为了响应google的推荐而已, 另外严格来讲
* 就应该在onPause存储数据,以免系统把我们进程杀掉导致数据丢失
* 其实结论是 不能在onStop onDestroy 调用类似lifecycleScope.launch{...}样式代码,因为那时候这个scope
* 正在被销毁,这样调用会导致括弧里代码不执行或者被强行中断
*
*/
否则跑不起来的
DataStore | Android 开发者 | Android Developers (google.cn)

package com.sky.testdatastore

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
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 androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * https://developer.android.google.cn/topic/libraries/architecture/datastore
 * 使用 Preferences DataStore 存储键值对
 * Preferences DataStore 实现使用 DataStore 和 Preferences 类将简单的键值对保留在磁盘上。
 * 创建 Preferences DataStore
 * 使用由 preferencesDataStore 创建的属性委托来创建 Datastore<Preferences> 实例。
 * 在您的 Kotlin 文件顶层调用该实例一次,便可在应用的所有其余部分通过此属性访问该实例。
 * 这样可以更轻松地将 DataStore 保留为单例。
 */
/**
 * 我们不难看出dataStore实际上是安卓架构组件的一部分,即便仅仅为了测试
 * 我们也不得不引入其它架构组件 协程支持 lifecycle支持
 */
// At the top level of your kotlin file:
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
val EXAMPLE_COUNTER = intPreferencesKey("example_counter")
class MainActivity : AppCompatActivity() {
    suspend fun incrementCounter(context:Context) {
        context.dataStore.edit { settings ->
            val currentCounterValue = settings[EXAMPLE_COUNTER] ?: 0
            settings[EXAMPLE_COUNTER] = currentCounterValue + 1
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val exampleCounterFlow: Flow<Int> = this.dataStore.data
            .map { preferences ->
                // No type safety.
                preferences[EXAMPLE_COUNTER] ?: 0
            }
        //读取datastore的值
        lifecycleScope.launchWhenStarted {
            exampleCounterFlow.collect {
                withContext(Dispatchers.Main.immediate){
                    findViewById<TextView>(R.id.textView).text = it.toString()
                }
            }
        }

        findViewById<Button>(R.id.buttonWrite)?.setOnClickListener {
            val c = this
            lifecycleScope.launch {
                incrementCounter(c)
            }
        }
        //以上 通过点击write按钮 这个counter就会一直增加 演示了dataStore的基本应用

        /**
         * 本人认为类型安全的方式 用于dataStore还不如用room呢,因为我们做安卓架构时 room必然是要使用的
         * 仅仅为了测试这个玩意也没啥意思,还挺费劲 所以就到这里了
         */
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容