【问题标题】:Ionic 4/5: exit from the app pressing back buttonIonic 4/5:按下后退按钮退出应用程序
【发布时间】:2023-04-23 05:18:01
【问题描述】:

仅在某个页面按下后退按钮时,我需要退出应用程序;特别是,假设我有 app.component.ts,并且我有一个名为 HomePage 的页面。在 app-routing.module.ts 我有这条路线:

const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', loadChildren: './public/home/home.module#HomePageModule' }
];

因此,无论用户打开应用程序,它都会将 HomePage 视为第一页。如果用户按下后退按钮,现在它会永远重新加载同一页面;我想抓住那个按下并退出应用程序。我尝试在 home.page.ts 中使用它,但没有任何反应:

backButtonSubscription: any;
this.backButtonSubscription = this.platform.backButton.subscribe(async () => {
console.log('lets exit!');
  navigator['app'].exitApp();
  });

甚至打印了console.log,就好像事件没有被捕获一样。我也试过这个:

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

但结果是一样的,所以我想知道如何解决它。我在网上找到了很多问题,但没有任何解释似乎可以解决此问题或提供解决方法。

感谢您的帮助!

【问题讨论】:

  • 你能把后退按钮的代码贴在html中吗?
  • 没有 HTML 代码,因为它应该抓住设备的后退按钮

标签: ionic-framework ionic4


【解决方案1】:

如果您使用的是 ionic 4 angular 。尝试这个 在 AppComponent -> 初始化应用程序 添加

this.platform.backButton.subscribeWithPriority(0, () => {
navigator[‘app’].exitApp();
});

这是一个例子

initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.platform.backButton.subscribeWithPriority(0, () => {
        navigator['app'].exitApp();
       
     });
    });
  }

【讨论】:

    【解决方案2】:

    在我的情况下,我使用电容器(离子 5),如果你也在使用电容器,请尝试这个

    import { Plugins } from '@capacitor/core';
    const { App } = Plugins;
    
    initializeApp() {
      App.addListener('backButton', () => {
        App.exitApp();
      });
    }
    

    【讨论】:

      【解决方案3】:

      离子 5。 另一种选择是使用Platform,对我来说,在使用标签的情况下效果很好:

      附言最好使用“init”服务而不是 app.component.ts 来保持应用程序初始化流程清晰明了

      constructor(
          private platform: Platform,
          private router: Router
      ) {
          this.platform.backButton.subscribeWithPriority(-1, () => {
              const url = this.router.url;
          
              if (url === '/tabs/not-home') {
                  this.router.navigate(['/tabs/home']);
              } else if (url === '/tabs/home') {
                  App.exitApp();
              }
          });
      }
      

      【讨论】:

        最近更新 更多