Ali Mhanna
Ali Mhanna

Reputation: 397

IONIC 5 hardware back button causes the app close

i'm using this code in my app.component.ts to handle hardware back button :

this.platform.backButton.subscribeWithPriority(10, (processNextHandler) => {
  console.log('Back press handler!');
  if (this.location.isCurrentPathEqualTo('/home')) {

    // Show Exit Alert!
    console.log('Show Exit Alert!');
    this.showExitConfirm();
    processNextHandler();
  } else {

    // Navigate to back page
    console.log('Navigate to back page');
    this.router.navigateByUrl['/home'];
    this.location.back();

  }

});

but it's not working it works only when lunch the app for the first time,later when I press back button the app closes ,I've tried many solutions but none of them works , both on simulator and real device with different versions of android (8,9,10) and same behaviour my ionic info :

     Ionic CLI                     : 5.4.16
   Ionic Framework               : @ionic/angular 5.6.13
   @angular-devkit/build-angular : 0.803.29
   @angular-devkit/schematics    : 8.3.29
   @angular/cli                  : 8.3.29
   @ionic/angular-toolkit        : 2.3.3

Cordova:

   Cordova CLI       : 10.0.0
   Cordova Platforms : android 9.1.0
   Cordova Plugins   : cordova-plugin-ionic-keyboard 2.2.0, cordova-plugin-ionic-webview 4.1.3, (and 14 other plugins)

Utility:

   cordova-res : 0.15.1
   native-run  : 1.4.0

System:

   Android SDK Tools : 26.1.1 ()
   NodeJS            : v12.16.1 ()
   npm               : 6.13.4
   OS                : Windows 10

Upvotes: 0

Views: 4476

Answers (2)

Ali Mhanna
Ali Mhanna

Reputation: 397

the same code works for me , the issue was in ionViewWillLeave() function , when I remove it , the code works

Upvotes: 0

Nischaya Sharma
Nischaya Sharma

Reputation: 471

This is my Working Code here

      this.plt.backButton.subscribeWithPriority(5, () => {
          console.log("Back button Clicked")
          var backRoute = this.prevRoute.getPreviousUrl();
          if (this.auth.isAuthenticated.value && backRoute == '/login') {
              navigator['app'].exitApp();
          } else {
              this.router.navigateByUrl(backRoute)
          }
      })

Upvotes: 0

Related Questions