implementation 'androidx.datastore:datastore-preferences:1.0.0'
val Context.dataStore by preferencesDataStore(name = "data_store")
//存储
dataStore.edit { edit ->
edit[stringPreferencesKey("data")] = "123456"
}
//读取
val data = dataStore.data.first()[stringPreferencesKey("data")]
Log.d(TAG.TAG,"data is $data")
2022-08-04 14:38:15.606 13419-13445/edu.test.demo D/Test-TAG: data is 123456
//存储
dataStore.edit { edit ->
edit[stringPreferencesKey("data")] = "123456"
}
//读取
val data = dataStore.data.first()[stringPreferencesKey("data")]
Log.d(TAG.TAG,"data is $data")
dataStore.edit { edit ->
edit[stringPreferencesKey("data")] = "123456789"
}
Log.d(TAG.TAG,"data is ${ dataStore.data.first()[stringPreferencesKey("data")]}")
2022-08-04 14:44:25.651 13552-13579/edu.test.demo D/Test-TAG: data is 123456
2022-08-04 14:44:25.657 13552-13579/edu.test.demo D/Test-TAG: data is 123456789
//存储
dataStore.edit { edit ->
edit[stringPreferencesKey("data")] = "123456"
}
//读取
val data = dataStore.data.first()[stringPreferencesKey("data")]
Log.d(TAG.TAG,"data is $data")
dataStore.updateData {
val mutablePreference = it.toMutablePreferences()
mutablePreference[stringPreferencesKey("data")] = "123456789"
mutablePreference.toPreferences()
}
Log.d(TAG.TAG,"data is ${ dataStore.data.first()[stringPreferencesKey("data")]}")
DataStore支持的存储类型从key上就可以看出,主要有七种,key类型以及调用方法如下,一眼就能看出来,就不一一
解释了:
val Context.dataStore : DataStore<Preferences> by preferencesDataStore(name = "dataStore_setting",
produceMigrations = { context ->
listOf( SharedPreferencesMigration(context, "sp_data"))
})
迁移之前我们可以看下sp文件,位置为data/data/包名/shared_prefs/sp文件名:
迁移之后,sp文件被删除,datastore文件出现,如下:
val data = dataStore.data.first()[stringPreferencesKey("mydata")]
Log.d(TAG.TAG,"sp->datastore,直接读取:$data")
2022-08-04 15:22:24.062 14131-14157/edu.test.demo D/Test-TAG: sp->datastore,直接读取:mydata123456