HarmonyOS 系统返回如何拦截?

如何拦截系统返回,需要两次再退出应用

阅读 456
1 个回答

如果要实现的是页面退出back事件,可以通过页面的onBackPress方法实现监听。仅有@Entry修饰的组件能获取返回事件的监听,可以通过重写onBackPress监听到返回事件的按下。

参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-custom-component-lifecycle-V5\#onbackpress

使用NavPathStack和NavDestination的非@Entry修饰的组件可使用onBackPressed方法,具体可参考文档:

https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-navdestination.md

import { promptAction, ShowDialogSuccessResponse } from '@kit.ArkUI';
import { common } from '@kit.AbilityKit';

@Entry
@Component
struct Index {
  @Provide('appPathStack') appPathStack: NavPathStack = new NavPathStack();
  @State currentIndex: number = 0
  context = getContext(this) as common.UIAbilityContext
  aboutToAppear(): void {
  }
  @Builder
  PageMap(name: string) {
    if (name === 'homePage') {
      // HomeComponent()
    }else if (name === 'stationDetailPage'){
      // StationDetailPage()
    }else if (name === 'userPersonInfo'){
      // HomeComponent()
    }
  }
  build() {
    Navigation(this.appPathStack) {
      Stack() {
        Flex({
          direction: FlexDirection.Column,
        }) {
          Tabs({ index: this.currentIndex }) {
            TabContent() {
              // HomeComponent()
            }
            TabContent() {
              // MapViewContainer()
            }

            TabContent() {
              // ChallengeView()
            }.tabBar()

            TabContent() {
              // ActivityView({ webViewController: $webViewController })
            }

            TabContent() {
              // PersonInfo()
            }
          }
          .layoutWeight(1)
          .barHeight(0)
          .scrollable(false)
          .onChange((index) => {
            this.currentIndex = index;
          })

          // CustomTabBar({ currentIndex: $currentIndex })
        }
        .width('100%')
        .height('100%')
        .backgroundColor($r('app.media.background'))
      }
    }
    .hideTitleBar(true)
    .navDestination(this.PageMap)
    .mode(NavigationMode.Stack)

  }

  onBackPress() {
    console.info('onBackPress:拦截');
    promptAction.showDialog({
      title: "提示",
      message: "确认退出?",
      buttons: [
        {
          text: "取消",
          color: "#000000"
        },
        {
          text: "退出",
          color: "#555555"
        }
      ]
    }).then((data: ShowDialogSuccessResponse) => {
      console.info('showDialog success, click button: ' + data.index);
      if (data.index == 1) {
        this.context.terminateSelf()
      }
    })
    return true;
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进