当前位置:   article > 正文

【AndroidX】DataStore API使用示例_android 如何让datastore api 大全

android 如何让datastore api 大全
  1. // Preferences DataStore
  2. implementation "androidx.datastore:datastore-preferences:1.0.0-alpha02"
  3. // Proto DataStore
  4. implementation "androidx.datastore:datastore-core:1.0.0-alpha02"
  5. implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9"
  6. implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2"//kotlin协程
  1. object DataStoreUtil {
  2. private var dataStore: DataStore<Preferences>? = null
  3. private const val dataStoreName: String = "user"
  4. /**
  5. * 写入数据
  6. */
  7. suspend fun writeDataToDataStore(context: Context, key: String, msg: String) {
  8. if (dataStore == null) {
  9. dataStore = context.createDataStore(dataStoreName)
  10. }
  11. val data = preferencesKey<String>(key)
  12. dataStore!!.edit { user ->
  13. user[data] = msg
  14. }
  15. }
  16. /**
  17. * 读取数据
  18. */
  19. fun readDataFromDataStore(context: Context, key: String): Flow<String> {
  20. if (dataStore == null) {
  21. dataStore = context.createDataStore(dataStoreName)
  22. }
  23. val data = preferencesKey<String>(key)
  24. return dataStore!!.data.map { preferences: Preferences -> preferences[data] ?: "" }
  25. }
  26. }
  1. class MainActivity : AppCompatActivity(), CoroutineScope by MainScope() {
  2. private val keys = arrayOf("测试1", "测试2", "测试3")
  3. private val tag: String = "DataStoreTest"
  4. override fun onCreate(savedInstanceState: Bundle?) {
  5. super.onCreate(savedInstanceState)
  6. setContentView(R.layout.activity_main)
  7. async {
  8. createData()
  9. }
  10. findViewById<TextView>(R.id.my_text).setOnClickListener {
  11. async {
  12. getData()
  13. }
  14. }
  15. }
  16. override fun onDestroy() {
  17. super.onDestroy()
  18. cancel()
  19. }
  20. private suspend fun createData() {
  21. DataStoreUtil.writeDataToDataStore(this, keys[0], "123")
  22. DataStoreUtil.writeDataToDataStore(this, keys[1], "456")
  23. DataStoreUtil.writeDataToDataStore(this, keys[2], "789")
  24. }
  25. private suspend fun getData() {
  26. val index = abs(Random(System.currentTimeMillis()).nextInt()) % 3
  27. var readDataFromDataStore: Flow<String> =
  28. DataStoreUtil.readDataFromDataStore(
  29. this,
  30. keys[index])
  31. readDataFromDataStore.collect {
  32. Log.d(tag, it)
  33. }
  34. }
  35. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/309322
推荐阅读
相关标签
  

闽ICP备14008679号