直接上实现代码

componentDidMount() {
    if (Platform.OS === 'android'){
      BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
    }
  }

 componentWillUnmount() {
    if (Platform.OS === 'android') {
      BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
    }
  }

  onBackAndroid = () => {
    //禁用返回键
    if(this.props.navigation.isFocused()) {//判断   该页面是否处于聚焦状态
        if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
          //最近2秒内按过back键,可以退出应用。
          // return false;
          BackHandler.exitApp();//直接退出APP
        }else{
          this.lastBackPressed = Date.now();
          ToastAndroid.show('再按一次退出应用', 1000);//提示
          return true;
        }
    }
  }

转载于:https://www.cnblogs.com/xiongxiaolong/p/10771139.html

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐