Ionic 2: How to handle the hardware back button which checks confirmation of Exit in app

前端 未结 7 633
你的背包
你的背包 2020-12-05 06:12

I am facing an issue how to handle the default mobile\'s back button which checks the confirmation while exiting from the application, if I pressed the back button there sho

7条回答
  •  北海茫月
    2020-12-05 06:34

    In app.component.ts

            @ViewChild(Nav) nav: Nav;
    
            constructor(private platform: Platform, private toastCtrl:   ToastController, private alertCtrl: AlertController) {
                platform.ready().then(() => {
                  // Okay, so the platform is ready and our plugins are available.
                  // Here you can do any higher level native things you might need
    
                  platform.registerBackButtonAction(() => {
    
    
                    //uncomment this and comment code below to to show toast and exit app
                    // if (this.backButtonPressedOnceToExit) {
                    //   this.platform.exitApp();
                    // } else if (this.nav.canGoBack()) {
                    //   this.nav.pop({});
                    // } else {
                    //   this.showToast();
                    //   this.backButtonPressedOnceToExit = true;
                    //   setTimeout(() => {
    
                    //     this.backButtonPressedOnceToExit = false;
                    //   },2000)
                    // }
    
                    if(this.nav.canGoBack()){
                      this.nav.pop();
                    }else{
                      if(this.alert){ 
                        this.alert.dismiss();
                        this.alert =null;     
                      }else{
                        this.showAlert();
                       }
                    }
                  });
                });
    
              }
    
              showAlert() {
              this.alert = this.alertCtrl.create({
                title: 'Exit?',
                message: 'Do you want to exit the app?',
                buttons: [
                  {
                    text: 'Cancel',
                    role: 'cancel',
                    handler: () => {
                      this.alert =null;
                    }
                  },
                  {
                    text: 'Exit',
                    handler: () => {
                      this.platform.exitApp();
                    }
                  }
                ]
              });
              alert.present();
            }
    
              showToast() {
                let toast = this.toastCtrl.create({
                  message: 'Press Again to exit',
                  duration: 2000,
                  position: 'bottom'
                });
    
                toast.onDidDismiss(() => {
                  console.log('Dismissed toast');
                });
    
                toast.present();
              }
    

提交回复
热议问题