欢迎加入开源鸿蒙PC社区:https://harmonypc.csdn.net/

欢迎在PC社区平台申请新建项目:https://atomgit.com/OpenHarmonyPCDeveloper

鸿蒙电脑开发ArkUI应用开发之会话记忆与窗口状态持久化

桌面软件有个不成文的礼貌:下次打开,还是上次的样子。窗口大小、正在编辑的内容、上次停在哪一栏,用户不会说,但他会记。Android 有 SharedPreferences,iOS 有 UserDefaults,H5 有 localStorage,Vue 项目里我一般再包一层 store 做节流。到了鸿蒙PC,这套东西还多一个维度:窗口本身的尺寸。

这篇讲怎么把“上次的样子”存下来:用什么存、存什么单位、什么时候落盘、版本变了怎么迁。代码是一个完整页面,保存、结束进程、重启恢复、清空四步都在真机上走过。鸿蒙电脑开发ArkUI应用,会话记忆这种不起眼的功能,往往决定用户觉得你专业不专业。

一、先选存储

鸿蒙的本地存储有三类常用:Preferences 键值、关系型数据库、应用沙箱文件。

Preferences 适合小、散、启动就要读的状态:窗口尺寸、上次打开的页签、开关项。关系型数据库适合要查询、要排序、数据量上千条的结构化数据。文件适合图片、日志、导出内容这类大对象。鸿蒙PC上,窗口尺寸是最容易被记住、也最容易被忽略的一项,用户把窗口拉到合适宽度,下次回来发现又变窄了,体验就断在这。

我的判断很简单:能在启动后一百毫秒内读完、总量不超过几十 KB 的,用 Preferences;其余的先想清楚再选。把一张图片塞进偏好,最后一定会为读写性能买单。

二、键从第一天就带版本

存储名用 pc_session,键值如下:

  • window_width:窗口宽度,单位 vp;
  • note:用户上次编辑的文本;
  • save_count:保存次数,用来验证是否真的读写成功;
  • saved_at:最后一次保存时间;
  • schema_version:数据版本。

最后这个键最容易被省掉。第一版只有三四个键时,觉得版本号多余;等到第二个版本要改字段名,才发现老用户的数据没法迁。版本号不占地方,加上。

三、读用同步,写要 flush

打开偏好和读值都用同步接口:

this.store = preferences.getPreferencesSync(this.ctx(), { name: STORE_NAME });
this.note = this.store.getSync(KEY_NOTE, this.note) as string;

同步读放在 aboutToAppear 里,第一帧就能拿到真实值。用异步接口也能做,但页面会先按默认值画一遍,再跳成上次的状态,用户能看到闪一下。

写入是 putSync 加 flushSync:

store.putSync(KEY_WIDTH, this.widthVp);
store.putSync(KEY_NOTE, this.note);
store.flushSync();

putSync 只改内存,flushSync 才落盘。连续改十个键,最后 flush 一次就够;每改一个都 flush,磁盘写入会被放大十倍。这个和 Android 的 apply() 与 commit() 是一个道理,只是这里把选择权交给你。鸿蒙PC上用户随手关窗口是常态,别把落盘拖到退出时再做,进程被回收时不保证还有机会。

四、窗口尺寸存 vp,不存 px

窗口 API 给的是 px。getWindowProperties().windowRect.width 是 px,windowSizeChange 回调里的 size.width 也是 px。直接把这个数存下来,换一台密度不同的机器,恢复出来的窗口大小就变了。

所以存之前先换算:

this.widthVp = Math.floor(this.getUIContext().px2vp(rect.width));

恢复时再换回去:

win.moveWindowTo(0, 0).then(() => {
  return win.resize(ui.vp2px(saved), ui.vp2px(760));
});

两个细节。第一,先 moveWindowTo(0, 0) 再 resize,否则窗口以当前左上角为基准往右长,宽窗口会出屏。第二,恢复前校验下限,小于应用声明的最小宽度就按最小值来,不要相信历史数据永远合法。

我只存了宽高,没存坐标。多屏、缩放比例变化、显示器拔插,都会让上次的坐标失效;尺寸相对安全,位置交给系统。鸿蒙PC的窗口可以拉到很宽,但应用自己声明了最小宽度,恢复时先把下限卡住,才不会出现内容被压扁的情况。

五、保存、重启、清空

第一张图是保存后的状态:窗口在 1240 vp,备注换成了另一段,保存次数变成 1,写入时间也记上了。

在这里插入图片描述

第二张是结束进程再启动之后。窗口回到 1240 vp,备注、次数、时间都在,状态行显示“窗口已恢复到上次的 1240 vp”。

在这里插入图片描述

第三张是清空偏好之后:备注回默认值,次数归零,窗口收回到 900 vp。

在这里插入图片描述

三步里最容易被忽略的是第三步。clearSync 清的是磁盘,界面上的 @State 不会自己变;如果只清存储不重置状态,用户看到的是“清空成功”,但输入框里还是旧内容。清完必须把内存状态一起改掉。

六、版本迁移

迁移逻辑放在读取业务字段之前,一次做完:

const oldVersion = store.getSync(KEY_VERSION, 1) as number;
if (oldVersion < CURRENT_VERSION) {
  if (store.hasSync('notes')) {
    const legacy = store.getSync('notes', '') as string;
    store.putSync(KEY_NOTE, legacy);
    store.deleteSync('notes');
  }
  store.putSync(KEY_VERSION, CURRENT_VERSION);
  store.flushSync();
}

这段代码不长,但顺序不能反:先判断版本,再搬字段,最后写新版本号并落盘。搬完不删旧键,数据会存两份,下次迁移又要判断一次。

七、几个坑

下面几个细节,鸿蒙电脑新手小白从0到1开发ArkUI应用时比 API 本身更容易翻车。

时间格式是第一个。图里显示的是 11/24/2026, 9:40:44 PM,因为直接用了 toLocaleString(),而它的默认格式跟系统 locale 走,界面是中文也一样。要给人看的时间,自己按 yyyy-MM-dd HH:mm 拼,别把默认格式直接摆到界面上。

第二个是异常。getPreferencesSync、getSync、putSync 都可能抛错,沙箱异常、磁盘满、类型不匹配都会走到 catch。我的做法是每个入口都包一层,失败时给状态行一句人话,而不是让页面白屏。

第三个是并发。多个页面共用一份偏好时,谁最后 flush 谁生效。我的习惯是只让一个地方写,其他页面通过状态同步;真要跨进程共享,先查清楚当前版本的支持范围,别想当然。

第四个是容量。偏好是给小数据准备的,别拿它存列表和图片。需要存大内容,把文件放沙箱,偏好里只存路径和摘要。

第五个是启动顺序。鸿蒙PC上应用重新拉起时,窗口尺寸可能先由系统给一个默认值,偏好读出来再改一次;如果界面在中间态渲染了复杂布局,用户会看到一次跳变。我的做法是先恢复窗口再显示主要内容,或者干脆给主区域一个稳定的骨架。

八、完整代码

pages/Index.ets 全文:

import { common } from '@kit.AbilityKit';
import { preferences } from '@kit.ArkData';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

const STORE_NAME: string = 'pc_session';
const KEY_WIDTH: string = 'window_width';
const KEY_NOTE: string = 'note';
const KEY_COUNT: string = 'save_count';
const KEY_TIME: string = 'saved_at';
const KEY_VERSION: string = 'schema_version';
const CURRENT_VERSION: number = 2;

@Entry
@Component
struct Index {
  @State widthVp: number = 0;
  @State note: string = '工作区:报表 / 本月';
  @State saveCount: number = 0;
  @State savedAt: string = '-';
  @State status: string = '正在读取本地偏好';
  @State version: number = CURRENT_VERSION;
  private mainWindow: window.Window | undefined = undefined;
  private store: preferences.Preferences | undefined = undefined;

  aboutToAppear(): void {
    this.openStore();
    this.bindWindow();
  }

  aboutToDisappear(): void {
    this.mainWindow?.off('windowSizeChange');
  }

  private ctx(): common.UIAbilityContext {
    return getContext(this) as common.UIAbilityContext;
  }

  private openStore(): void {
    try {
      this.store = preferences.getPreferencesSync(this.ctx(), { name: STORE_NAME });
      this.migrate();
      this.note = this.store.getSync(KEY_NOTE, this.note) as string;
      this.saveCount = this.store.getSync(KEY_COUNT, 0) as number;
      this.savedAt = this.store.getSync(KEY_TIME, '-') as string;
      this.status = this.saveCount > 0 ? '已读到上次会话,窗口尺寸稍后恢复' : '本地还没有保存过会话';
    } catch (e) {
      const err = e as BusinessError;
      this.status = `打开偏好失败:${err.code}`;
    }
  }

  private migrate(): void {
    const store = this.store;
    if (!store) {
      return;
    }
    const oldVersion = store.getSync(KEY_VERSION, 1) as number;
    if (oldVersion < CURRENT_VERSION) {
      if (store.hasSync('notes')) {
        const legacy = store.getSync('notes', '') as string;
        store.putSync(KEY_NOTE, legacy);
        store.deleteSync('notes');
      }
      store.putSync(KEY_VERSION, CURRENT_VERSION);
      store.flushSync();
    }
    this.version = CURRENT_VERSION;
  }

  private bindWindow(): void {
    window.getLastWindow(this.ctx()).then((win: window.Window) => {
      this.mainWindow = win;
      const rect = win.getWindowProperties().windowRect;
      this.widthVp = Math.floor(this.getUIContext().px2vp(rect.width));
      win.on('windowSizeChange', (size: window.Size) => {
        this.widthVp = Math.floor(this.getUIContext().px2vp(size.width));
      });
      this.restoreWindow();
    }).catch((err: BusinessError) => {
      this.status = `取窗口失败:${err.code}`;
    });
  }

  private restoreWindow(): void {
    const store = this.store;
    if (!store) {
      return;
    }
    const saved = store.getSync(KEY_WIDTH, 0) as number;
    if (saved >= 720) {
      this.applyWidth(saved).then(() => {
        this.status = `窗口已恢复到上次的 ${saved} vp`;
      });
    }
  }

  private applyWidth(target: number): Promise<void> {
    const win = this.mainWindow;
    if (!win) {
      return Promise.resolve();
    }
    const ui = this.getUIContext();
    try {
      return win.moveWindowTo(0, 0).then(() => {
        return win.resize(ui.vp2px(target), ui.vp2px(760));
      }).catch((err: BusinessError) => {
        this.status = `调整窗口失败:${err.code}`;
      });
    } catch (e) {
      const err = e as BusinessError;
      this.status = `调整窗口失败:${err.code}`;
      return Promise.resolve();
    }
  }

  private saveSession(): void {
    const store = this.store;
    if (!store) {
      this.status = '偏好还没有打开,先看日志';
      return;
    }
    try {
      const next = this.saveCount + 1;
      store.putSync(KEY_WIDTH, this.widthVp);
      store.putSync(KEY_NOTE, this.note);
      store.putSync(KEY_COUNT, next);
      store.putSync(KEY_TIME, new Date().toLocaleString());
      store.putSync(KEY_VERSION, CURRENT_VERSION);
      store.flushSync();
      this.saveCount = next;
      this.savedAt = new Date().toLocaleString();
      this.status = `已保存:宽 ${this.widthVp} vp,第 ${next} 次`;
    } catch (e) {
      const err = e as BusinessError;
      this.status = `保存失败:${err.code}`;
    }
  }

  private clearSession(): void {
    const store = this.store;
    if (!store) {
      return;
    }
    try {
      store.clearSync();
      store.flushSync();
      this.saveCount = 0;
      this.savedAt = '-';
      this.note = '工作区:报表 / 本月';
      this.status = '偏好已清空,窗口回到 900 vp';
      this.applyWidth(900);
    } catch (e) {
      const err = e as BusinessError;
      this.status = `清空失败:${err.code}`;
    }
  }

  @Builder
  SectionTitle(title: string, desc: string) {
    Column({ space: 4 }) {
      Text(title)
        .fontSize(16)
        .fontWeight(FontWeight.Medium)
        .fontColor('#1A1A1A')
        .width('100%')
      Text(desc)
        .fontSize(12)
        .fontColor('#8A8A8E')
        .width('100%')
    }
    .width('100%')
    .alignItems(HorizontalAlign.Start)
  }

  build() {
    Column() {
      Row({ space: 10 }) {
        Text('鸿蒙PC 会话记忆实验台')
          .fontSize(18)
          .fontWeight(FontWeight.Medium)
          .fontColor('#1A1A1A')
        Text('preferences')
          .fontSize(12)
          .fontColor('#6B6B70')
          .backgroundColor('#F0F1F3')
          .padding({ left: 8, right: 8, top: 4, bottom: 4 })
          .borderRadius(4)
        Blank()
        Text(`当前窗口 ${this.widthVp} vp`)
          .fontSize(12)
          .fontColor('#6B6B70')
        Text(`数据版本 v${this.version}`)
          .fontSize(12)
          .fontColor('#0A59F7')
      }
      .width('100%')
      .height(58)
      .padding({ left: 20, right: 20 })
      .backgroundColor(Color.White)

      Divider().color('#E5E6E8')

      Column({ space: 16 }) {
        Column({ space: 10 }) {
          this.SectionTitle('备注', '输入框里的内容和其他状态一起落盘,重启后按原样回来')
          TextInput({ text: this.note, placeholder: '写点会被记住的内容' })
            .height(38)
            .fontSize(13)
            .onChange((value: string) => {
              this.note = value;
            })
          Row({ space: 8 }) {
            Button('换一段备注')
              .fontSize(13)
              .height(32)
              .backgroundColor('#F0F1F3')
              .fontColor('#1A1A1A')
              .onClick(() => {
                this.note = this.note === '工作区:报表 / 本月'
                  ? '工作区:配色稿 / 第 3 版'
                  : '工作区:报表 / 本月';
              })
            Button('保存会话')
              .fontSize(13)
              .height(32)
              .backgroundColor('#0A59F7')
              .onClick(() => {
                this.saveSession();
              })
            Button('清空偏好')
              .fontSize(13)
              .height(32)
              .backgroundColor('#F0F1F3')
              .fontColor('#1A1A1A')
              .onClick(() => {
                this.clearSession();
              })
          }
          .width('100%')
          Text(this.status)
            .fontSize(12)
            .fontColor('#6B6B70')
            .width('100%')
        }
        .width('100%')
        .padding(16)
        .backgroundColor(Color.White)
        .borderRadius(10)

        Row({ space: 16 }) {
          Column({ space: 10 }) {
            this.SectionTitle('窗口尺寸', '尺寸是 px,存之前先换成 vp,不然换台机器就错位')
            Row({ space: 8 }) {
              Text(`${this.widthVp} vp`)
                .fontSize(26)
                .fontWeight(FontWeight.Medium)
                .fontColor('#1A1A1A')
              Blank()
              Text(`约 ${Math.round(this.widthVp * 1.75)} px`)
                .fontSize(12)
                .fontColor('#8A8A8E')
            }
            .width('100%')
            Row({ space: 8 }) {
              Button('900 宽')
                .fontSize(13)
                .height(32)
                .layoutWeight(1)
                .backgroundColor('#F0F1F3')
                .fontColor('#1A1A1A')
                .onClick(() => {
                  this.applyWidth(900);
                })
              Button('1240 宽')
                .fontSize(13)
                .height(32)
                .layoutWeight(1)
                .backgroundColor('#F0F1F3')
                .fontColor('#1A1A1A')
                .onClick(() => {
                  this.applyWidth(1240);
                })
            }
            .width('100%')
            Text('保存时记录的是 vp 值,恢复时再用 vp2px 换回去,密度变了也不会偏。')
              .fontSize(12)
              .fontColor('#8A8A8E')
              .lineHeight(18)
              .width('100%')
          }
          .layoutWeight(1)
          .padding(16)
          .backgroundColor(Color.White)
          .borderRadius(10)
          .alignItems(HorizontalAlign.Start)

          Column({ space: 8 }) {
            this.SectionTitle('本地存储', '一个应用一个偏好文件,键值都是同步写')
            Row() {
              Text('存储名').fontSize(12).fontColor('#8A8A8E').width(90)
              Text(STORE_NAME).fontSize(12).fontColor('#3A3A3C').fontFamily('monospace')
            }
            .width('100%')
            Row() {
              Text('保存次数').fontSize(12).fontColor('#8A8A8E').width(90)
              Text(`${this.saveCount}`).fontSize(12).fontColor('#3A3A3C')
            }
            .width('100%')
            Row() {
              Text('上次保存').fontSize(12).fontColor('#8A8A8E').width(90)
              Text(this.savedAt)
                .fontSize(12)
                .fontColor('#3A3A3C')
                .layoutWeight(1)
                .maxLines(1)
                .textOverflow({ overflow: TextOverflow.Ellipsis })
            }
            .width('100%')
            Row() {
              Text('数据版本').fontSize(12).fontColor('#8A8A8E').width(90)
              Text(`v${this.version}`).fontSize(12).fontColor('#3A3A3C')
            }
            .width('100%')
          }
          .layoutWeight(1)
          .padding(16)
          .backgroundColor(Color.White)
          .borderRadius(10)
          .alignItems(HorizontalAlign.Start)
        }
        .width('100%')
        .alignItems(VerticalAlign.Top)
      }
      .width('100%')
      .layoutWeight(1)
      .padding(20)
      .alignItems(HorizontalAlign.Start)
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#F2F3F5')
  }
}

会话记忆这个功能,用户不会夸,但缺了会被骂。它也不难,难在单位、版本、落盘时机这些细节上。把这些想清楚,代码量其实很小。

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐