Ionic 4:硬件后退按钮重新加载应用程序

Ionic 4: Hardware Back Button Reloading Application

从事项目并陷入问题:

硬件后退按钮重新加载应用程序(我在此应用程序中使用 Angular 路由器)。

我的退出应用程序代码:

  ionViewDidEnter(){
      this.subscription = this.platform.backButton.subscribe(()=>{
          navigator['app'].exitApp();
      });
  }

  ionViewWillLeave(){
        this.subscription.unsubscribe();
  }

虽然相同的逻辑在其他应用程序中工作。但是在这个应用程序中它重新加载应用程序而不是退出它。

P.S:我也试过将它放入 platform.ready() 但没有成功。

使用 IONIC 4,开发了新方法 subscribeWithPriority 来处理软后退按钮和硬后退按钮之间的竞争。尝试像下面这样修改您的代码:

 this.platform.backButton.subscribeWithPriority(1, () => {
        navigator['app'].exitApp();
 });

subscribeWithPriority() stops the propagation of the event after its execution and if we subscribe with high priority and execute our prefered navigation instead of default one then it is going to work as you want.

更多参考文档:
https://github.com/ionic-team/ionic/commit/6a5aec8b5d76280ced5e8bb8fd9ea6fe75fe6795
https://medium.com/@aleksandarmitrev/ionic-hardware-back-button-nightmare-9f4af35cbfb0

更新:

  • 尝试使用这个新版本的 exitApp cordova plugin。我没有 自己尝试过,但从人气来看看起来很有前途。
  • 也尝试从 Navcontroller 清空页面堆栈或转到您的主屏幕,这似乎导致重新加载带有侧边菜单和标签页的应用...this.navCtrl.pop() / this._navCtrl.navigateBack('HomeScreen'),然后调用 exitApp.

注意: 选项卡和侧边菜单,因为它们有自己的路由模块,确实给应用程序导航带来了很多复杂性。

你的应用有侧边菜单吗?我很好奇,因为这似乎也是我遇到这个问题的时候。

如果您查看检查器,您会看到 window.history 的长度为 1。

我在我的一些应用程序中没有看到它,但我有侧边菜单设置的应用程序是这样操作的 - 在主页上,如果你按回屏幕变白,然后它会重新加载应用程序。

就像我说的那样,查看检查器显示有一个历史可以退回到它正在尝试做的事情,无论那个历史步骤是什么,它只是将它向前推回到主页,这使得我想知道是不是侧边菜单设置了自己对导航系统的控制。

我可能说了一些措辞不佳的术语,但由于我自己还没有解决这个问题,所以我想我只是让你知道我发现了什么......希望它能帮助你前进。

在我的场景中,我什至没有尝试在返回代码时退出 - 我只是注意到如果我继续按返回,该应用程序会显示 "reboot"。

已解决:

正如 @rtpHarry 侧边菜单/选项卡模板所提到的那样,它具有导致应用程序在根页面上自行重新加载的历史记录。我能够通过清除历史记录来解决这个问题。

ionViewDidEnter(){
  navigator['app'].clearHistory();    
}

在您的根页面上只需清除您的历史记录,您的硬件后退按钮将关闭应用程序而不是重新加载它。

这解释了 Ionic 5(我认为也是 4.6+)的解决方案。

private backButtonSub: Subscription;

ionViewDidEnter() {
  this.backButtonSub = this.platform.backButton.subscribeWithPriority(
    10000,
    () => {
        // do your stuff
    }
  );
}

ionViewWillLeave() {
  this.backButtonSub.unsubscribe();
}

还保留

IonicModule.forRoot({
  hardwareBackButton: true
}),

true(默认)在你的app.module.ts

来源: