Hardware back button with Ionic 4


#42

@cherzog that’s exactly what I’m using. When I inspect the device via devtools and go to the console I can see the logs when back button on Android is pressed. I can also minimize the app using AppMinimize.

Maybe it has to do with you using it on a modal page? Modals always seem to have issues. Try doing it in something that isn’t a modal (ie home page or app component like suggested above).

Also, why are you putting this in a modal? I’m having a hard time understanding what a use case would be.


#43

It’s the modal, yes. It also happens when you use another overlay. A select, for example. You have the sub-page open, open the Select and press the Back button. The subpage disappears and the select overlay remains open. I’ve updated the git hub repo …


#44

Am i doing something wrong? In app.component i have the following code, still nothing shows on console in devtools(chrome) when back button pressed on device.

image

UPDATE: This solution actually works, i was just running the app on device in debug mode with “ionic cordova run android --device -l --debug” command and i guess that’s messed it up. After running it without --debug it worked like a charm.


#45

Same here. No event fired.

To be clear: I start “ionic serve” and use the browser on the android device.


#46

Here’s my workaround:

import { ModalController } from '@ionic/angular';
import { Injectable } from '@angular/core';
import { CanDeactivate, Router, ActivatedRouteSnapshot } from '@angular/router';
import { Location } from '@angular/common';

@Injectable({
  providedIn: 'root'
})
export class BackButtonService implements CanDeactivate<any> {

  constructor( 
    private modalCtrl: ModalController,
    private alertCtrl: AlertController,
    private popoverCtrl: PopoverController,
    private readonly location: Location,
    private readonly router: Router) { }

  canDeactivate(component: any, currentRoute: ActivatedRouteSnapshot): Promise<boolean> {
    return new Promise((resolve) => {
      this.modalCtrl.getTop()
      .then((modalElement) => {
        if (modalElement) {
          modalElement.dismiss();
          const currentUrlTree = this.router.createUrlTree([], currentRoute);
          const currentUrl = currentUrlTree.toString();
          this.location.go(currentUrl);
          resolve(false);
        } else {
          this.alertCtrl.getTop()
          .then((alertElement) => {
            if (alertElement) {
              alertElement.dismiss();
              const currentUrlTree = this.router.createUrlTree([], currentRoute);
              const currentUrl = currentUrlTree.toString();
              this.location.go(currentUrl);
              resolve(false);
            } else {
              this.popoverCtrl.getTop()
              .then((popoverElement) => {
                if (popoverElement) {
                  popoverElement.dismiss();
                  const currentUrlTree = this.router.createUrlTree([\*], currentRoute);
                  const currentUrl = currentUrlTree.toString();
                  this.location.go(currentUrl);
                  resolve(false);
                } else {
                  resolve(true);
                }
              });
            }
          });
        }
      });
    });
  }
}

In App-routing.module.ts:

  {
    path: 'subpage',
    loadChildren: './subpage/subpage.module#SubpagePageModule',
    canDeactivate: [BackButtonService]
  },

This is enough in my case. You can certainly extend it to other types (menus, alerts, etc).


#47

Hai GameAppsBD .This is not working in tabs home page ,But it is working fine in login page.Here is my code

backButtonEvent(){
this.platform.backButton.subscribe(async () => {
// close action sheet
try {
const element = await this.actionSheetCtrl.getTop();
if (element) {
element.dismiss();
return;
}
} catch (error) {
}

  this.routerOutlets.forEach((outlet: IonRouterOutlet) => {
      if (outlet && outlet.canGoBack()) {
          outlet.pop();

      } else  {
          if (new Date().getTime() - this.lastTimeBackPress < this.timePeriodToExit) {
              // this.platform.exitApp(); // Exit from app
              navigator['app'].exitApp(); // work in ionic 4

          } else {
            this.showAlert()
              this.lastTimeBackPress = new Date().getTime();
          }
      }
  });
  this.lastBack = Date.now();

});
}


#48

This is not Working in Tabs Home Page.Working Fine in Login Page . Here is my code`.Please Help Me

  backButtonEvent(){
    this.platform.backButton.subscribe(async () => {
      // close action sheet
      try {
          const element = await this.actionSheetCtrl.getTop();
          if (element) {
              element.dismiss();
              return;
          }
      } catch (error) {
      }

      this.routerOutlets.forEach((outlet: IonRouterOutlet) => {
          if (outlet && outlet.canGoBack()) {
              outlet.pop();

          } else  {
              if (new Date().getTime() - this.lastTimeBackPress < this.timePeriodToExit) {
                  navigator['app'].exitApp(); // work in ionic 4

              } else {
                this.showAlert()
                  this.lastTimeBackPress = new Date().getTime();
              }
          }
      });
      this.lastBack = Date.now();
  });
  }

#49

My app doesn’t close when hitting the backButton in the homePage. I tried this :

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

And it works…
But it also works in the other pages, so instead of having the normal “back” behaviour, the backButton exits the app from everywhere in the app…

I had the idea of unsubscribing when moving from the homepage, but the problem is that when I go back to the home page, the ngOnInit is not fired, so I can’t resubscribe…

Another idea is to access the name of the page where the user is (router??) from the backButtonEvent function, to know which behaviour to have

Had you this sort of problem, did you solve it ??

Thanks