HarmonyOS 首选项示例

HarmonyOS
2025-01-09 14:10:50
浏览
收藏 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');
  }
}
  • 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.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
// 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%')
  }
}
  • 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.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158.
  • 159.
  • 160.
  • 161.
  • 162.
  • 163.
  • 164.
  • 165.
  • 166.
  • 167.
  • 168.
  • 169.
  • 170.
  • 171.
  • 172.
  • 173.
  • 174.
  • 175.
  • 176.
  • 177.
  • 178.
  • 179.
  • 180.
  • 181.
  • 182.
  • 183.
  • 184.
  • 185.
  • 186.
  • 187.
  • 188.
  • 189.
  • 190.
  • 191.
  • 192.
  • 193.
  • 194.
  • 195.
  • 196.
  • 197.
  • 198.
  • 199.
  • 200.
  • 201.
  • 202.
  • 203.
  • 204.
  • 205.
  • 206.
  • 207.
  • 208.
  • 209.
  • 210.
  • 211.
分享
微博
QQ
微信
回复
2025-01-09 16:04:18


相关问题
首选项preferences相关
678浏览 • 1回复 待解决
HarmonyOS 首选项回调失效
665浏览 • 1回复 待解决
HarmonyOS TaskPool使用首选项报错
1159浏览 • 1回复 待解决
HarmonyOS 首选项报错数据报错
656浏览 • 1回复 待解决
HarmonyOS 创建首选项报错code:15500000
777浏览 • 1回复 待解决
HarmonyOS 获取首选项取值的方式
808浏览 • 1回复 待解决
HarmonyOS 首选项超长string存储失败
611浏览 • 1回复 待解决
首选项存储问题,为什么会报错?
936浏览 • 1回复 待解决
HarmonyOS 模拟器使用首选项能力异常
700浏览 • 1回复 待解决
HarmonyOS 用户首选项是线程安全的吗
903浏览 • 1回复 待解决
首选项获取实例,实例是否为单例
2376浏览 • 1回复 待解决
错误码15500000(首选项)如何处理?
1966浏览 • 1回复 待解决