Harmonyos5应用开发实战——应用启动与数据初始化(part2)

134 阅读1分钟
3. 页面路径解析

根据传入的want对象解析页面路径,获取商户ID、桌号等信息,并根据情况清空购物车。

resolvePagePath(want: Want) {
  // 从want中获取传入的链接信息
  let uri = want?.uri;
  let parameters = want?.parameters;
  console.info(`uri is: ${uri}`);
  if (uri) {
    //解析通过router跳转的页面
    // 商户id
    let storeId = want.parameters?.sid as string;
    console.info(`storeId is: ${storeId}`);
    AppStorage.setOrCreate('storeId', storeId);
    // 桌号
    let tableId = want.parameters?.tid as string;
    console.info(`tableId is: ${tableId}`);
    AppStorage.setOrCreate('tableId', tableId);
    // 扫码进入清空购物车
    AppStorage.setOrCreate('qrCodeFlag', true);
  } else if (parameters?.url) {
    let formCardJump: FormCardJump = JSON.parse(parameters?.params.toString() || '');
    formCardJump.id = new Date().getTime()
    AppStorage.setOrCreate('formCardJump', formCardJump);
  }
}
4. 推送令牌获取

尝试获取推送令牌,若成功则记录日志,失败则记录错误信息。

try {
  const pushToken: string = await pushService.getToken();
  hilog.info(0x0000, 'testTag', 'Succeeded in getting push token');
} catch (err) {
  let e: BusinessError = err as BusinessError;
  hilog.error(0x0000, 'testTag', 'Failed to get push token: %{public}d %{public}s', e.code, e.message);
}
5. 窗口创建与设置

在窗口创建时,加载主页面,设置窗口全屏,并获取状态栏和导航条的避让区域高度。

onWindowStageCreate(windowStage: window.WindowStage): void {
  // Main window is created, set main page for this ability
  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

  windowStage.loadContent('pages/Index', async (err) => {
    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.');
    let windowClass: window.Window = windowStage.getMainWindowSync(); // 获取应用主窗口
    // 设置窗口全屏
    await windowClass.setWindowLayoutFullScreen(true);
    let type = window.AvoidAreaType.TYPE_SYSTEM; // 以状态栏避让为例
    let avoidArea = windowClass.getWindowAvoidArea(type);
    let windowTopHeight = px2vp(avoidArea.topRect.height);
    AppStorage.setOrCreate('windowTopHeight', windowTopHeight);
    type = window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR; // 以导航条避让为例
    avoidArea = windowClass.getWindowAvoidArea(type);
    let windowBottomHeight = px2vp(avoidArea.bottomRect.height);
    AppStorage.setOrCreate('windowBottomHeight', windowBottomHeight);
    PersistentStorage.persistProp('userIconPath', 'userImage.jpg');
  });
}

通过以上功能的实现,HarmonyOS 5应用在启动时能够高效地完成数据初始化和窗口设置,为用户提供良好的使用体验。