HarmonyOS 首选项示例

HarmonyOS
2天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
fox280

参考示例:

//EntryAbility.ets
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import hilog from '@ohos.hilog';
import UIAbility from '@ohos.app.ability.UIAbility';
import Want from '@ohos.app.ability.Want';
import window from '@ohos.window';
import { BusinessError } from '@ohos.base';
import dataPreferences from '@ohos.data.preferences';

let preferences: dataPreferences.Preferences = {} as dataPreferences.Preferences;

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
  }

  onDestroy() {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
  }

  onWindowStageCreate(windowStage: window.WindowStage) {
    //组件创建时加载本地数据
    try {
      let options: dataPreferences.Options = {
        name: 'myStore'
      };
      preferences = dataPreferences.getPreferencesSync(this.context, options);
      AppStorage.setOrCreate("preferences", preferences);
    } catch (err) {
      let code = (err as BusinessError).code;
      let message = (err as BusinessError).message;
      console.error(`Failed to get preferences. Code:${code},message:${message}`);
    }
    //写入数据
    try {
      if (preferences.hasSync('startup')) {
        console.info("The key 'startup' is contained.");
      } else {
        console.info("The key 'startup' does not contain.");
        // 此处以此键值对不存在时写入数据为例
        preferences.putSync('startup', 'auto');
      }
    } catch (err) {
      let code = (err as BusinessError).code;
      let message = (err as BusinessError).message;
      console.error(`Failed to check the key 'startup'. Code:${code}, message:${message}`);
    }
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    windowStage.loadContent('pages/Index', (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    });
  }

  onWindowStageDestroy() {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }

  onForeground() {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground() {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }
}
// Index.ets
import dataPreferences from '@ohos.data.preferences';
import { BusinessError } from '@ohos.base';
import { DEFAULT } from '@ohos/hypium';
import router from '@ohos.router';

const usernameV: string = "admin";
const passwordV: string = "123456";

//加载等待
async function sleepFunction(): Promise<void> {
  try {
    const result: string = await new Promise(() => {
      setTimeout(() => {
        router.pushUrl({ url: 'pages/Loading' });
      }, 5000);
    });
  } catch (e) {
    console.error(`Get exception: ${e}`);
  }
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  private inputAccountValue: string = "";
  private inputPassword: string = "";
  @State flag1: boolean = false;
  @State flag2: boolean = false;
  private username: string = "";
  private password: string = "";
  @StorageLink("preferences") preferences: dataPreferences.Preferences = {} as dataPreferences.Preferences;

  aboutToAppear() {
    //获取首选项的用户数据
    try {
      let usernameVal: Object = this.preferences.getSync('username', 'default');
      this.username = usernameVal as string;
      if (this.username == "default") {
        this.username = "";
      }
      let passwordVal: Object = this.preferences.getSync('password', 'default');
      this.password = passwordVal as string;
      if (this.password == "default") {
        this.password = "";
      }
      let savePasswordVal: Object = this.preferences.getSync('savePassword', 'default');
      if (savePasswordVal != DEFAULT) {
        this.flag1 = savePasswordVal as boolean;
      }
      let autoLoginVal: Object = this.preferences.getSync('autoLogin', 'default');
      if (autoLoginVal != DEFAULT) {
        this.flag2 = autoLoginVal as boolean;
      }
      console.info(`Succeeded in getting value of 'info'. usernameVal: ${usernameVal}.passwordVal: ${passwordVal}.savePasswordVal: ${savePasswordVal}.autoLoginVal: ${autoLoginVal}.`);
    } catch (err) {
      let code: number = (err as BusinessError).code;
      let message: string = (err as BusinessError).message;
      console.error(`Failed to get value of 'info'. Code:${code}, message:${message}`);
    }
  }

  onPageShow() {
    //每次显示这个页面时,如果勾选了自动登录,则自动登录
    if (this.flag2 == true && this.username == usernameV && this.password == passwordV) {
      sleepFunction()
    }
  }

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        Row() {
          Text("账号:")
            .margin({ top: 20 })
            .fontSize(20)
          TextInput({ placeholder: '请输入账号', text: this.username })
            .onChange((value: string) => {
              this.inputAccountValue = value;
            })
            .width(250)
            .margin({ top: 20 })
            .type(InputType.Normal)
        }

        Row() {
          Text("密码:")
            .margin({ top: 20 })
            .fontSize(20)
          TextInput({ placeholder: '请输入密码', text: this.password })
            .onChange((value: string) => {
              this.inputPassword = value;
            })
            .width(250)
            .margin({ top: 20 })
            .type(InputType.Password)
        }

        Row() {
          Row() {
            Toggle({ type: ToggleType.Checkbox, isOn: this.flag1 })
              .margin({ top: 13 })
              .width(20)
              .onClick(() => {
                this.flag1 = !this.flag1;
              })
            Text("记住密码")
              .margin({ top: 10 })
              .fontSize(15)
          }
          .margin({ right: 50 })

          Row() {
            Toggle({ type: ToggleType.Checkbox, isOn: this.flag2 })
              .margin({ top: 13 })
              .width(20)
              .onClick(() => {
                if (this.flag2 == false) {
                  this.flag1 = true;
                }
                this.flag2 = !this.flag2;
              })
            Text("自动登录")
              .margin({ top: 10 })
              .fontSize(15)
          }
          .margin({ left: 50 })
        }

        Button('登录')
          .width(150)
          .margin({ top: 20 })
          .onClick(() => {
            if (this.inputAccountValue == usernameV && this.inputPassword == passwordV) {
              try {
                //添加数据,写入账号
                if (this.preferences.hasSync('username')) {
                  //如果存在就更改账号
                  this.preferences.put('username', this.inputAccountValue, (err: BusinessError) => {
                    if (err) {
                      console.error(`Failed to put the value of 'username'. Code:${err.code},message:${err.message}`);
                      return;
                    }
                  })
                } else {
                  // 此处以此键值对不存在时写入数据为例
                  this.preferences.putSync('username', this.inputAccountValue);
                }
                //点击记住密码,持久化账号密码
                if (this.flag1 == true) {
                  //写入密码
                  if (this.preferences.hasSync('password')) {
                    //如果存在就更改密码
                    this.preferences.put('password', this.inputPassword, (err: BusinessError) => {
                      if (err) {
                        console.error(`Failed to put the value of 'password'. Code:${err.code},message:${err.message}`);
                        return;
                      }
                    })
                  } else {
                    // 键值对不存在时写入数据
                    this.preferences.putSync('password', this.inputPassword);
                  }
                  //写入记住密码状态
                  if (this.preferences.hasSync('savePassword')) {
                  } else {
                    // 键值对不存在时写入数据
                    this.preferences.putSync('savePassword', this.flag1);
                  }
                  //写入自动登录状态
                  if (this.flag2 == true) {
                    if (this.preferences.hasSync('autoLogin')) {
                    } else {
                      // 此处以此键值对不存在时写入数据为例
                      this.preferences.putSync('autoLogin', this.flag1);
                    }
                  } else {
                    this.preferences.deleteSync('autoLogin');
                  }
                } else {
                  this.preferences.deleteSync('password');
                  this.preferences.deleteSync('savePassword');
                }
                //数据持久化
                this.preferences.flush((err: BusinessError) => {
                  if (err) {
                    console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
                    return;
                  }
                  console.info('Succeeded in flushing.');
                })
              } catch (err) {
                let code = (err as BusinessError).code;
                let message = (err as BusinessError).message;
                console.error(`Failed to check the key 'save'. Code:${code}, message:${message}`);
              }
              router.pushUrl({ url: 'pages/Loading' });
            } else {
              console.error(`Failed to check the key 'login'`);
            }
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
分享
微博
QQ
微信
回复
2天前
相关问题
首选项preferences相关
212浏览 • 1回复 待解决
HarmonyOS TaskPool使用首选项报错
628浏览 • 1回复 待解决
HarmonyOS 首选项回调失效
165浏览 • 1回复 待解决
HarmonyOS 创建首选项报错code:15500000
349浏览 • 1回复 待解决
HarmonyOS 首选项报错数据报错
190浏览 • 1回复 待解决
HarmonyOS 获取首选项取值的方式
247浏览 • 1回复 待解决
HarmonyOS 首选项超长string存储失败
167浏览 • 1回复 待解决
首选项存储问题,为什么会报错?
453浏览 • 1回复 待解决
首选项获取实例,实例是否为单例
2093浏览 • 1回复 待解决
HarmonyOS 用户首选项是线程安全的吗
498浏览 • 1回复 待解决
HarmonyOS 模拟器使用首选项能力异常
281浏览 • 1回复 待解决
错误码15500000(首选项)如何处理?
1481浏览 • 1回复 待解决