HarmonyOS 鸿蒙Next 通过首选项记录应用是否第一次启动
拜托各位大神帮我看看吧,写了两天了还是没实现,通过首选项记录App第一次启动时弹窗请求权限,当同意后,下一次启动则不再询问,一直不成功。
@Entry
@Component
struct LauncherPage {
private context?:common.UIAbilityContext
pre?: preferences.Preferences;
@State isAgree:string = ''
private timerId: number = 0;
dialogController:CustomDialogController = new CustomDialogController({
builder:CustomDialogComponent({
cancel:()=>{
this.onCancel()
},
confirm:()=>{
this.onConfirm()
}
}),
alignment:DialogAlignment.Bottom,
offset:{dx:0, dy:-24},
autoCancel:false
})
async aboutToAppear() {
preferencesUtil.getPreferences()
this.isAgree = await preferencesUtil.get('isAgree')
console.log('[LauncherPage] aboutToAppear isAgree:' + this.isAgree)
if(this.isAgree === 'yes') {
this.dialogController.close()
}
else
this.dialogController.open()
}
onCancel(){
this.context?.terminateSelf()
}
onConfirm(){
this.isAgree = 'yes'
this.saveIsAgree(this.isAgree)
this.jumpToAdvertisingPage()
}
jumpToAdvertisingPage() {
this.timerId = setTimeout(() => {
router.pushUrl({
url: 'pages/HomePage'
}).catch((error: Error) => {
Logger.error('LauncherPage', 'LauncherPage pushUrl error ' + JSON.stringify(error));
});
}, 3000);
}
saveIsAgree(value:string){
preferencesUtil.save('isAgree',value)
}
build() {
Stack() {
Image($r('app.media.ic_launcher_background'))
.width('100%')
.height('100%')
Column() {
Image($r('app.media.ic_logo'))
.width($r('app.float.launcher_logo_size'))
.height($r('app.float.launcher_logo_size'))
.margin({ top: '16.2%' })
Text($r('app.string.healthy_life_text'))
.width($r('app.float.launcher_life_text_width'))
.height($r('app.float.launcher_life_text_height'))
.healthyLifeTextStyle(FontWeight.Bold,
0.1,
$r('app.float.launcher_text_title_size'),
$r('app.color.launcher_text_title_color'))
.margin({ top: '0.5%' })
Text($r('app.string.healthy_life_introduce'))
.height('2.7%')
.healthyLifeTextStyle(FontWeight.Normal,
3.4,
$r('app.float.launcher_text_introduce_size'),
$r('app.color.launcher_text_introduce_color'))
.opacity($r('app.float.launcher_text_opacity'))
.margin({ top: '1.3%' })
}
.height('100%')
.width('100%')
}
}
}
// Healthy living text common styles.
@Extend(Text) function healthyLifeTextStyle (fontWeight: number,
textAttribute: number, fontSize: Resource, fontColor: Resource) {
.fontWeight(fontWeight)
.letterSpacing(textAttribute)
.fontSize(fontSize)
.fontColor(fontColor)
}
工具类
import { common } from '@kit.AbilityKit'
import { preferences, ValueType } from '@kit.ArkData'
let pre: preferences.Preferences | null = null;
export class PreferencesUtil{
context:common.UIAbilityContext = getContext(this) as common.UIAbilityContext
constructor() {
this.getPreferences()
console.log('constructor')
}
async getPreferences(){
pre = await preferences.getPreferences(this.context,'myPre')
}
async save(key:string,value:preferences.ValueType){
// if(pre != undefined){
// await pre.put('isAgree', value)
// await pre.flush()
// console.log('[save]'+value)
// }
if(!pre){
console.info('preferences不存在')
this.getPreferences
}
if(pre?.has(key)){
console.info('key:'+key+' 存在')
}
pre?.put(key,value)
pre?.flush()
}
async get(key:string) {
let resValue:ValueType = ''
if(!pre) {
this.getPreferences()
}
resValue = await pre?.get(key,'default') as string
return resValue
}
}
export default new PreferencesUtil()
求助一下,我这到底哪里写得不对呢?
更多关于HarmonyOS 鸿蒙Next 通过首选项记录应用是否第一次启动的实战教程也可以访问 https://www.itying.com/category-93-b0.html
判断是否弹窗申请权限可以根据返回的authResults来判断,具体参考文档【https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-permissionrequestresult-V5】
1、首次申请拒绝:authResults返回值为-1,dialogShownResults返回值为true
2、拒绝后再次申请:authResults返回值为-1,dialogShownResults返回值为false
使用如下demo验证可行:
import { router } from '@kit.ArkUI';
import { abilityAccessCtrl } from '@kit.AbilityKit';
[@Entry](/user/Entry)
[@Component](/user/Component)
struct PageA {
[@State](/user/State) message: string = 'PageA';
dialogController: CustomDialogController | null = new CustomDialogController({
builder: CustomDialogExample({
cancel: () => {
this.onCancel()
},
confirm: () => {
this.onAccept()
}
}),
cancel: this.existApp,
autoCancel: true,
onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
console.info("reason=" + JSON.stringify(dismissDialogAction.reason))
console.log("dialog onWillDismiss")
if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
dismissDialogAction.dismiss()
}
if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
dismissDialogAction.dismiss()
}
},
alignment: DialogAlignment.Center,
offset: { dx: 0, dy: -20 },
customStyle: false,
cornerRadius: 20,
width: 300,
height: 200,
borderWidth: 1,
borderStyle: BorderStyle.Dashed, //使用borderStyle属性,需要和borderWidth属性一起使用
borderColor: Color.Blue, //使用borderColor属性,需要和borderWidth属性一起使用
backgroundColor: Color.White,
shadow: ({
radius: 20,
color: Color.Grey,
offsetX: 50,
offsetY: 0
}),
})
// 在自定义组件即将析构销毁时将dialogController置空
aboutToDisappear() {
this.dialogController = null // 将dialogController置空
}
onCancel() {
console.info('Callback when the first button is clicked')
}
onAccept() {
console.info('Callback when the second button is clicked')
}
existApp() {
console.info('Click the callback in the blank area')
}
aboutToAppear(): void {
let atManager = abilityAccessCtrl.createAtManager();
atManager.requestPermissionsFromUser(getContext(this), ['ohos.permission.CAMERA'])
.then(data => {
console.log('data------------------------', JSON.stringify(data))
let result: Array<number> = data.authResults;
let hasPermissions1 = true;
result.forEach(item => {
if (item === -1) {
hasPermissions1 = false;
}
})
if (hasPermissions1) {
console.info("hasPermissions1");
if (this.dialogController != null) {
this.dialogController.open()
}
} else {
console.info(" not hasPermissions1");
}
}).catch(() => {
return;
});
}
build() {
Column() {
Text(this.message)
Button('to pageB')
.onClick(() => {
router.pushUrl({
url: 'pages/1017/PageB'
})
})
}
.height('100%')
.width('100%')
}
}
[@CustomDialog](/user/CustomDialog)
struct CustomDialogExample {
controller?: CustomDialogController
cancel: () => void = () => {
}
confirm: () => void = () => {
}
build() {
Column() {
Text('这是自定义弹窗')
.fontSize(30)
.height(100)
Button('点我关闭弹窗')
.onClick(() => {
if (this.controller != undefined) {
this.controller.close()
}
})
.margin(20)
}
}
}
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>
更多关于HarmonyOS 鸿蒙Next 通过首选项记录应用是否第一次启动的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
1 aboutToAppear 方法第一行 preferencesUtil.getPreferences() 前面加上await. 这样能正常获得数据了。
2 确保CustomDialogComponent 里面的confirm 被执行了。
3 aboutToAppear 加async这个有点扯。后面学习更多了之后再改改。现在优先解决问题。
preferencesUtil这个类要设计没设计,要方便没方便。还影响你开发,我的建议是趁早删了
HarmonyOS 鸿蒙Next 可以通过首选项(Preferences)来记录应用是否第一次启动。以下是实现方法:
-
导入模块:
使用
import { preferences } from '@kit.ArkData';
导入用户首选项模块。 -
获取Preferences实例:
调用
preferences.getPreferencesSync(context, options)
方法获取Preferences实例,其中context
为应用上下文,options
为包含实例名称的配置选项。 -
检查并记录启动状态:
在获取到Preferences实例后,使用
hasSync
方法检查是否存在记录应用启动状态的键(如"firstLaunch"
)。如果不存在,则表示是第一次启动,可以使用putSync
方法记录该状态。 -
示例代码:
let options: preferences.Options = { name: 'appLaunchStatus' }; let dataPreferences: preferences.Preferences = preferences.getPreferencesSync(this.context, options); if (!dataPreferences.hasSync('firstLaunch')) { dataPreferences.putSync('firstLaunch', true); // 执行第一次启动的相关操作 }
如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html 。