0
votes

I am facing problem with the hardware back button on android. I am working with Ionic CLI 4.12.0 I want to exit the app when user on homePage and clicks back button. But back button event is not firing up. It navigate to login page then restarts the app. I am using Tabs template in my app. I have tried many answers of stackoverflow that claims solution to the similar problem. I have setup code in app component as following:



@ViewChild(IonRouterOutlet) routerOutlet: IonRouterOutlet;

  constructor(private platform: Platform){
      this.platform.backButton.subscribeWithPriority(0, () => {
      console.log("back button clicked");
      navigator["app"].exitApp();
})
}
2
Why don't you use the NavigationController?Sinan Samet
I am using NavigationController also. I want to implement 'Click back again to exit the app' functionality. But back button event is not firing at first place.Supinder Singh
Ah okay my bad. According to this answer forum.ionicframework.com/t/…, you have to use navCtrl.back() afterwards. Maybe that helps?Sinan Samet
In newer version of Ionic 4, routing is handled by Angular router. In my upper reply NavigationController means angular navigation for me. In your suggested solution back button event is fired then navCtrl.back() is executed, but in my problem back button event is never fired at first place.Supinder Singh
Is you app have SideMenu or TABS?Najam Us Saqib

2 Answers

0
votes

Finally I found the answer of my question:


  ionViewDidEnter() {
    document.addEventListener("backbutton",function(e) {
      console.log("disable back button called from tab 1")
    }, false);
}
0
votes

I have simple app with menu and this is my solution: 1) in app.components.ts i have hardware back button implemented to get back on every page:

constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private nav: NavController
  ) {
    this.initializeApp();
  }

initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.platform.backButton.subscribeWithPriority(1, () => {
        this.nav.back();
      });
    });
  }

2) this additional code in home.page.ts is to close app with hardware back button(look at priority):

  ngOnInit() {
    this.platform.backButton.subscribeWithPriority(2, () => {
      console.log('BACK button pressed');
      navigator['app'].exitApp();
    });
  }