Wednesday 21 July 2021

Android Back Button to Exit App in Ionic

There are at least two ways to have Android hardware back button to exit app. I am using Ionic 5 at the time of writing this.

1) Using IonRouterOutlet to check through history stack
import { IonRouterOutlet, Platform } from '@ionic/angular';
import { Plugins } from '@capacitor/core';
const { App } = Plugins;

export class HomePage {
   constructor(private platform: Platform, private routerOutlet: IonRouterOutlet){
   
      . . .
   
      this.platform.backButton.subscribeWithPriority(-1, () => {
         if (!this.routerOutlet.canGoBack()) {
            navigator['app'].exitApp();
            //App.exitApp();   // if using Capacitor framework, we can use Plugins component
         }
      });
   }

   . . .
}

2) Using Location from Angular library
import { Platform } from '@ionic/angular';
import { AfterViewInit, OnDestroy } from "@angular/core";
import { Subscription } from "rxjs";
import { Location } from '@angular/common';

export class HomePage implements OnDestroy, AfterViewInit {
   backButtonSubscription: Subscription;
    
   constructor(private platform: Platform, private location: Location){   
      . . .
   }
   
   ngAfterViewInit() {
      this.backButtonSubscription = this.platform.backButton.subscribe(() => {
         if (this.location.isCurrentPathEqualTo("HOME_PAGE_URL")){
            navigator['app'].exitApp();
         }
      });
   }
   
   ngOnDestroy() {
      this.backButtonSubscription.unsubscribe();
   }

   . . .

}

References:
Ionic Framework Documentation - Hardware Back Button
How To Exit App On Back Press | Ionic 4

Further reading:
Ionic 5 handle back hardware event to confirm exit by user