赞
踩
- // Preferences DataStore
- implementation "androidx.datastore:datastore-preferences:1.0.0-alpha02"
-
- // Proto DataStore
- implementation "androidx.datastore:datastore-core:1.0.0-alpha02"
-
- implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9"
- implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2"//kotlin协程
- object DataStoreUtil {
-
- private var dataStore: DataStore<Preferences>? = null
- private const val dataStoreName: String = "user"
-
- /**
- * 写入数据
- */
- suspend fun writeDataToDataStore(context: Context, key: String, msg: String) {
- if (dataStore == null) {
- dataStore = context.createDataStore(dataStoreName)
- }
-
- val data = preferencesKey<String>(key)
- dataStore!!.edit { user ->
- user[data] = msg
- }
- }
-
- /**
- * 读取数据
- */
- fun readDataFromDataStore(context: Context, key: String): Flow<String> {
- if (dataStore == null) {
- dataStore = context.createDataStore(dataStoreName)
- }
-
- val data = preferencesKey<String>(key)
- return dataStore!!.data.map { preferences: Preferences -> preferences[data] ?: "" }
- }
- }
- class MainActivity : AppCompatActivity(), CoroutineScope by MainScope() {
-
- private val keys = arrayOf("测试1", "测试2", "测试3")
- private val tag: String = "DataStoreTest"
-
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_main)
- async {
- createData()
- }
- findViewById<TextView>(R.id.my_text).setOnClickListener {
- async {
- getData()
- }
- }
- }
-
- override fun onDestroy() {
- super.onDestroy()
- cancel()
- }
-
- private suspend fun createData() {
- DataStoreUtil.writeDataToDataStore(this, keys[0], "123")
- DataStoreUtil.writeDataToDataStore(this, keys[1], "456")
- DataStoreUtil.writeDataToDataStore(this, keys[2], "789")
- }
-
- private suspend fun getData() {
- val index = abs(Random(System.currentTimeMillis()).nextInt()) % 3
-
- var readDataFromDataStore: Flow<String> =
- DataStoreUtil.readDataFromDataStore(
- this,
- keys[index])
- readDataFromDataStore.collect {
- Log.d(tag, it)
- }
- }
- }
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。