Android Preferences DataStore和现有的Room实现可以通过以下步骤来解决:
dependencies {
implementation "androidx.preference:preference-ktx:1.1.1"
implementation "androidx.datastore:datastore-preferences:1.0.0-alpha06"
implementation "androidx.datastore:datastore-core:1.0.0-alpha06"
implementation "androidx.room:room-runtime:2.2.6"
kapt "androidx.room:room-compiler:2.2.6"
}
class MyApp : Application() {
val dataStore: DataStore by lazy {
applicationContext.createDataStore(name = "settings")
}
}
object PreferencesKeys {
val USER_NAME = preferencesKey("user_name")
val IS_LOGGED_IN = preferencesKey("is_logged_in")
}
class PreferenceStore(private val dataStore: DataStore) {
val userNameFlow: Flow = dataStore.data.map { preferences ->
preferences[PreferencesKeys.USER_NAME] ?: ""
}
val isLoggedInFlow: Flow = dataStore.data.map { preferences ->
preferences[PreferencesKeys.IS_LOGGED_IN] ?: false
}
suspend fun setUserName(userName: String) {
dataStore.edit { preferences ->
preferences[PreferencesKeys.USER_NAME] = userName
}
}
suspend fun setIsLoggedIn(isLoggedIn: Boolean) {
dataStore.edit { preferences ->
preferences[PreferencesKeys.IS_LOGGED_IN] = isLoggedIn
}
}
}
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
@Entity(tableName = "users")
data class User(
@PrimaryKey val id: Int,
val name: String
)
@Dao
interface UserDao {
@Query("SELECT * FROM users")
fun getAllUsers(): Flow>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertUser(user: User)
}
class MainActivity : AppCompatActivity() {
private lateinit var preferenceStore: PreferenceStore
private lateinit var userDao: UserDao
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val dataStore = (application as MyApp).dataStore
preferenceStore = PreferenceStore(dataStore)
val db = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java, "my-db"
).build()
userDao = db.userDao()
// 读取偏好设置
lifecycleScope.launch {
preferenceStore.userNameFlow.collect { userName ->
// 处理用户名变化
}
}
// 写入偏好设置
lifecycleScope.launch {
preferenceStore.setUserName("John Doe")
}
// 读取数据库
lifecycleScope.launch {
userDao.getAllUsers().collect { users ->
// 处理用户列表变化
}
}
// 写入数据库
lifecycleScope.launch {
val user = User(1, "John Doe")
userDao.insertUser(user)
}
}
}
通过以上步骤,你可以将Android Preferences DataStore和现有的Room实现结合起来,实现偏好设置和数据库的读写操作。