HarmonyOS 在组件或类中内如何监听前后台切换

能否在一个组件内或者自定义的class类中监听到APP前后台切换呢?

HarmonyOS
2024-12-27 14:52:33
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
Excelsior_abit

可以试着在UIAbility中的onForeground和onBackground用AppStorage.setOrCreate<boolean>('view', true)来监听应用前后台。https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/uiability-lifecycle-V5#foreground%E5%92%8Cbackground%E7%8A%B6%E6%80%81

在组件中监听这个值的变化,参考demo:

@Entry
@Component
struct Index {
  @State message: string = 'Hello World'
  @StorageLink('view') 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.info(""+this.isOnForeground)
      })
  }
  change() {
    if (this.isOnForeground) {
      console.info('in header')
    } else {
      console.info('in end')
    }
  }
}
  • 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.
分享
微博
QQ
微信
回复
2024-12-27 15:32:01
相关问题
如何组件监听App前后台切换
1263浏览 • 0回复 待解决
Component如何监听应用前后台切换
2200浏览 • 1回复 待解决
HarmonyOS应用前后台状态切换事件监听
1762浏览 • 1回复 待解决
HarmonyOS 组件如何感知app前后台切换
1186浏览 • 0回复 待解决
HSP如何感知前后台切换
2856浏览 • 1回复 待解决
监听应用前后台状态切换的api吗
2389浏览 • 1回复 待解决
HarmonyOS 前后台进程切换时机
797浏览 • 1回复 待解决
HarmonyOS 相机模块的前后台切换
760浏览 • 1回复 待解决
HarmonyOS SDK后台模式监听
940浏览 • 1回复 待解决
HarmonyOS 如何监听app从后台切换到前台
1092浏览 • 1回复 待解决
如何判断应用处于前后台
1267浏览 • 1回复 待解决
如何判断前后台进程,有知道的吗?
2661浏览 • 1回复 待解决
HarmonyOS 关于切换前后相机的问题
828浏览 • 1回复 待解决