Rishi Raj
Rishi Raj

Reputation: 21

How to close application using hardware back button

The hardware back button does not closes the application in Ionic 4 either with cordova or capacitor.

This feature was working in Ionic 3 but now in Ionic 4 it only navigates back.

Is there a way out to close the application using hardware back button.

Upvotes: 0

Views: 1553

Answers (2)

Vinod Gehlot
Vinod Gehlot

Reputation: 117

Here is the solution : in homepage.ts

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



ionViewWillLeave(){ 
this.subscription.unsubscribe(); }

Upvotes: 0

ram12393
ram12393

Reputation: 1258

In the app.component.ts, you need below code, when you press your mobile hardware back button

initializeApp() {
        this.platform.ready().then(() => {
          this.statusBar.backgroundColorByHexString("#efa300");
          this.splashScreen.hide();
          this.platform.backButton.subscribe(() => {
            this.routerOutlets.forEach((outlet: IonRouterOutlet) => {
              if (this.router.url === '/home') {  //mention your router url(when to exit your app)
                if (new Date().getTime() - this.lastTimeBackPress < this.timePeriodToExit) {
                  navigator['app'].exitApp();
                } 
              }
            });
          })
        });
      }

Upvotes: 1

Related Questions