HarmonyOS 普通对象怎么监听组件生命周期

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

可以参考这个:https://gitee.com/openharmony/docs/blob/7ad8e708cebd3e4a43979e97de160da9c0533316/zh-cn/application-dev/reference/apis/js-apis-arkui-observer.md

//entryability.ets
import window from '@ohos.window';
import { BusinessError } from '@ohos.base';


interface Data {
  window: window.Window
}

export default class EntryAbility extends UIAbility {
  private window: window.Window | undefined = undefined
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {

    const that : EntryAbility = this
    this.context.eventHub.on("getWindow", (data: Data) => {
      if(that.window != undefined)
      {
        data.window = that.window
      }
      else {
        hilog.info(0x0000, 'testTag', '%{public}s', 'that.subWindowStage == undefined');
      }
    })
  }

  onDestroy(): void {
  }

  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/Index2', (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) ?? '');
      // 获取应用主窗口。
      let windowClass: window.Window = window.findWindow("observer0");
      this.window = windowClass
      windowStage.getMainWindow((err: BusinessError, data) => {
        let errCode: number = err.code;
        if (errCode) {
          console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err));
          return;
        }
      })
    });
  }
  onWindowStageDestroy(): void {
  }
}
//index2.ets
import common from '@ohos.app.ability.common';
import window from '@ohos.window';
import UIContext, { UIObserver } from '@ohos.ArkUI.UIContext';
import observer from '@ohos.ArkUI.observer';
import router from '@ohos.router';

interface Data11 {
  window: window.Window | null
}

@Entry
@Component
struct Index2 {
  private abilityContext: common.UIAbilityContext | null = null;
  private uiContext: UIContext.UIContext | null = null
  private context = getContext(this) as common.UIAbilityContext;

  testFunc(info: observer.RouterPageInfo) {
    console.log("[testFunc][UI-in-Pages] called by: Index2: " + `${info.index}` + ", name: " + `${info.name}` + ", path: " + `${info.path}` + ", state: " + `${info.state}`+ ",context: " + `${info.context}` );
  }
  aboutToAppear() {
    console.log("[Test] aboutToAppear before createWindow");
    this.abilityContext = getContext(this) as common.UIAbilityContext;
    let data : Data11 = {
      window: null
    };
    this.abilityContext.eventHub.emit("getWindow", data);
    if (data.window) {
      this.uiContext = data.window.getUIContext()
    } else {
      this.uiContext = null
    }
    router.getState()
  }
  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Text('这是Index')
        .fontSize(20)
        .fontWeight(FontWeight.Bold)

      Button('ObserverOn')
        .margin({top:5})
        .onClick(() => {
          let observer: UIObserver | null = this.uiContext ? this.uiContext.getUIObserver() : null
          if (observer) {
            // 注册router页面监听,范围为当前UIContext
            console.log("[Test] set observer to ON");
            observer.on('routerPageUpdate', this.testFunc)
          }
        })
      Button('ObserverOff')
        .margin({top:5})
        .onClick(() => {
          let observer: UIObserver | null = this.uiContext ? this.uiContext.getUIObserver() : null
          if (observer) {
            // 注册router页面监听,范围为当前UIContext
            console.log("[Test] set observer to OFF");
            observer.off('routerPageUpdate', this.testFunc)
          }
        })

      Button('pushUrl PageOne')
        .margin({ top: 5})
        .onClick(() => {
          router.pushUrl({
            url: 'pages/PageOne2',
          })
        })

    }
    .width('100%')
    .height('100%')
    .backgroundColor('#FFBFE5C5')
  }
}
//PageOne2.ets

@Entry
@Component
struct PageOne2 {
  @State message: string = '22222222222';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}
分享
微博
QQ
微信
回复
2天前
相关问题
监听Ability生命周期
1180浏览 • 1回复 待解决
swiper切换监听生命周期
988浏览 • 1回复 待解决
如何监听subwindow生命周期
371浏览 • 1回复 待解决
HarmonyOS 监听所有page的生命周期
469浏览 • 1回复 待解决
如何监听全局Ability生命周期
378浏览 • 1回复 待解决
如何监听AbilitySlice的生命周期
5121浏览 • 1回复 待解决
HarmonyOS能否全局监听页面的生命周期
603浏览 • 1回复 待解决
Dialog组件生命周期问题
330浏览 • 1回复 待解决
HarmonyOS Navigation跳转的组件生命周期
605浏览 • 2回复 待解决
如何知晓navigation组件生命周期
262浏览 • 1回复 待解决
JMS 消息怎么设置生命周期呢?
2710浏览 • 1回复 待解决
HarmonyOS 模块生命周期管理
232浏览 • 1回复 待解决
弹窗组件无法调用生命周期接口
2246浏览 • 1回复 待解决
HarmonyOS 生命周期不触发
47浏览 • 1回复 待解决
HarmonyOS 生命周期回调触发
49浏览 • 1回复 待解决