Preference首选项
- 首选项:首选项为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。数据存储形式为键值对,键的类型为字符串型,值的存储数据类型包括数字型、字符型、布尔型以及这3种类型的数组类型。
Demo记录APP首次启动
- 通常用于首次启动后弹出隐私协议弹窗,然后记录后,下次启动不在弹窗。
- 调用页面
import SpUtils from './utils/SpUtils'
@Entry
@Component
struct PagePreference {
@State msg: string = ""
onPageShow(): void {
this.msg = "当前数据" + SpUtils.isFirst()
}
build() {
Column() {
Button("保存数据")
.id('PagePreferenceHelloWorld')
.margin({ top: 20 })
.fontSize(20)
.fontWeight(FontWeight.Bold)
.onClick(() => {
SpUtils.setFirst()
this.msg = "保存数据"
})
Button("获取数据")
.id('PagePreferenceHelloWorld')
.margin({ top: 20 })
.fontSize(20)
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.msg = "获取数据" + SpUtils.isFirst()
})
Button("清空数据")
.id('PagePreferenceHelloWorld')
.margin({ top: 20 })
.fontSize(20)
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.msg = "清空数据"
SpUtils.clearData()
})
Text(this.msg)
.fontSize(25)
.margin({ top: 20 })
}
.height('100%')
.width('100%')
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 工具类SpUtils
import preferences from '@ohos.data.preferences'
export default class SpUtils {
private static KEY_DATA = "key_data"
private static SP_NAME = "data"
private static sp: preferences.Preferences = preferences.getPreferencesSync(getContext(this), {
name: SpUtils.SP_NAME
})
//设置启动状态
static setFirst() {
SpUtils.sp.putSync(SpUtils.KEY_DATA, false)
SpUtils.sp.flush()
}
//是否首次启动
static isFirst(): boolean {
let data = SpUtils.sp.getSync(SpUtils.KEY_DATA, true) as boolean
return data
}
//清空该表中的所有数据
static clearData() {
SpUtils.sp.clearSync()
SpUtils.sp.flush()
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
评论记录:
回复评论: