应用的前后台生命周期与页面和组件无关,组件仅能感知aboutToAppear和aboutToDisappear事件。若组件需要感知应用的前后台切换,可以设置一个应用前后台状态的变量。在UIAbility中对应的生命周期函数中更改此变量,并在组件中监听AppStorage状态变量的变化,执行相应的逻辑。

参考代码如下:

// EntryAbility中
export default class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage): void {
    AppStorage.setOrCreate<boolean>('isOnForeground', undefined);
  }


  onForeground(): void {
    AppStorage.set<boolean>('isOnForeground', true);
  }


  onBackground(): void {
    AppStorage.set<boolean>('isOnForeground', false);
  }
}
@Entry
@Component
struct ComponentListenFrontAndBack {
  @State message: string = 'Hello World';
  @StorageLink('isOnForeground') isOnForeground: boolean = true;


  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        Vid({ isOnForeground: this.isOnForeground })
      }
      .width('100%')
    }
    .height('100%')
  }
}


@Component
struct Vid {
  @Watch('change') @Link isOnForeground: boolean;
  @State message: string = 'video';


  build() {
    Text('message')
      .fontSize(50)
      .fontWeight(FontWeight.Bold)
      .onClick(() => {
        this.message += this.isOnForeground;
        console.log('' + this.isOnForeground);
      })
  }


  change() {
    if (this.isOnForeground) {
      console.log('The component is on foreground.');
    } else {
      console.log('The component is on background.');
    }
  }
}
Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐