Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic 4: Hardware Back Button Reloading Application

Working on a Project and stuck in an Issue:

Hardware Back Button Reloading Application (I am using Angular Router in this application).

My Code to Exit Application:

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

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

While same logic Working in other applications. but in this application its reloading the application not exiting it.

P.S: i have also tried it to put in platform.ready() but no luck.

like image 854
Najam Us Saqib Avatar asked Aug 23 '19 14:08

Najam Us Saqib


2 Answers

Solved:

As Mention by @rtpHarry template of SideMenu / Tabs have History which leads application to Reload it self on root page. i was able to solve this by clearing History.

ionViewDidEnter(){
  navigator['app'].clearHistory();    
}

on Your Root Page just Clear your history and your Hardware Back Button will close the Application instead of Reloading it.

like image 63
Najam Us Saqib Avatar answered Sep 20 '22 09:09

Najam Us Saqib


With IONIC 4, there is new method subscribeWithPriority developed to handle race between soft & hard back button. Try modifying your code like below:

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

subscribeWithPriority() stops the propagation of the event after its execution and if we subscribe with high priority and execute our prefered navigation instead of default one then it is going to work as you want.

More reference docs for details:
https://github.com/ionic-team/ionic/commit/6a5aec8b5d76280ced5e8bb8fd9ea6fe75fe6795
https://medium.com/@aleksandarmitrev/ionic-hardware-back-button-nightmare-9f4af35cbfb0

UPDATES:

  • Try using this new version of exitApp cordova plugin. I haven't tried myself but looks promising from popularity.
  • Also try to empty the page stack from Navcontroller or go to your home screen, seems like that's causing the reload for app with sidemenu's & tab pages... this.navCtrl.pop() / this._navCtrl.navigateBack('HomeScreen'), and then call exitApp.

NOTE: Tabs & SideMenu as those have its own routing module does create lot of complexity with app navigation.

like image 29
Amith Kumar Avatar answered Sep 18 '22 09:09

Amith Kumar