V4 : back-button doesn't exit app [solved--Tutorial]

This worked for me too. :slight_smile:

If you need to use hardware back button navigation with tabs:

private listenOnHardwareBackButton() {
    if (this.platform.is('android')) {
        this.platform.backButton.subscribeWithPriority(0, () => {
            if (!this.counter) {
                const appStr = 'app';
                navigator[appStr].exitApp();
            }
            this.navCtrl.back();
        });
        this.router.events
            .pipe(filter(event => event instanceof NavigationStart))
            .subscribe((event: NavigationStart) => {
                if (event.navigationTrigger === 'popstate') {
                    this.counter--;
                } else {
                    this.counter++;
                }
            });
    }
}
1 Like

what does mean [β€˜app’]

This solution works from version ionic/angular 4.7.2 https://github.com/ionic-team/ionic/releases/tag/v4.7.2
I was on 4.6.1 and no events were firing

can you tel me where to implement this code, im failing to implement it

Hardware back button is called globally even if you use in specific page. So best place to use it is in app component.

backButtonEvent() {
    if (this.platform.is('android')) {
        this.platform.backButton.subscribeWithPriority(0, () => {
        console.log('this.router.url', this.router.url);
        if (this.router.url === '/home' ) {
           navigator['app'].exitApp();
        }  else {
         this.navCtrl.navigateBack('/' + 'componetToGo');
        }
      });
    }
  }

And where do we call β€œbackButtonEvent()” method in the app?

Basically you are registering the back button event so you can call this from appComponet ngOnit().