Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Exit Ionic 4 app using device back button?

Tags:

angular

ionic4

I'm want to close the application when I press the back button on the android device, but nothing was happening and I found a solution by writing the following code to the home page. And home page is loaded in my tabs, and it does work as it closes the app. but it is closing the app from all the other pages also. Please help!

ionViewDidEnter() {
    this.subscription = this.platform.backButton.subscribe(() => {
      navigator["app"].exitApp();
    });
  }
  ionViewDidLeave() {
    this.subscription.unsubscribe();
  }
like image 459
Hussain Arthuna Avatar asked Mar 08 '19 23:03

Hussain Arthuna


2 Answers

Exit Ionic4 Application Using Device Back Button

I tried this method and it is working fine for me.

When the view is entering I am subscribing it into variable and when it leaves then unsubscribe. So that the exiting app on the back button will execute for that particular page only.

constructor(private platform: Platform){}
backButtonSubscription;
ionViewWillEnter() {
  this.backButtonSubscription = this.platform.backButton.subscribe(async () => {
  navigator['app'].exitApp();
  });
 }
}
ionViewDidLeave() {
 this.backButtonSubscription.unsubscribe();
}
like image 127
Ashish Avatar answered Sep 30 '22 19:09

Ashish


Updated Answer

It seems things are a bit different with Ionic4. They have added the subscribeWithPriority() feature.

You can use this snippet to which you can set on the homepage so that the back button exits:

 this.platform.backButton.subscribeWithPriority(1, () => {
        navigator['app'].exitApp();
 });

You could easily put a toast onto this either as a timeout that exits if you press it twice in a short period of time, or have a confirm button to exit.

Original Answer

This is a long shot, but I was looking for something similar to this recently.

The feature I wanted to implement was the "press back again to exit" that I had seen in a few apps.

This is normally triggered by the user pressing back all the back to the start of the app. Then pressing it again shows a toast warning them one more back and you will exit the app. This stops the user accidentally exiting the app.

I know you are looking for Ionic 4 and that's what I code in as well but what I found is tagged as Ionic 3. It doesn't make any mention of Ionic 4 even though it has been updated as recently as 2 months ago, so I guess you should try it out if you're still trying to solve this problem:

  • https://github.com/heidji/ionic3-android-backbutton

FYI I found this at the end of a lengthy discussion on the Ionic Framework forum.

like image 36
rtpHarry Avatar answered Sep 30 '22 19:09

rtpHarry