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

前端 未结 7 607
你的背包
你的背包 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:31

    Kinda late to the party... But there is more to back button other than closing the pushed pages, specially for project with several tab pages.

    Sometimes a page is pushed NOT into the root page, but in one of the tab page's navCtrl. So we have to check for all of them.

    Also, if no page or menu is open, we should circle around the most recently used tabs (similar to Instagram app) and go back to the previous tab. Moreover, we should not go back to each tab more than once (similar to Instagram)

    I got inspired by the answers here and created a comprehensive method that handles all necessary features:

    • Side menu: Closes the side menu if it was open
    • Pushed pages: Closes any pages that might have been pushed on any of the tab pages’ nav controller
    • Switch between tabs: If the menu was closed, and there was no pushed page, it should take the user back to the previous recently used tab using a stack.
    • Show alert: If there was no previous recently used tab, an alert box should ask the user if they want to exit.

    The details are in this blog post

    A demo code can be downloaded from my github.

    0 讨论(0)
  • 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();
              }
    
    0 讨论(0)
  • 2020-12-05 06:34

    Ionic latest version 3.xx

    app.component.ts file:

    import { Platform, Nav, Config, ToastController } from 'ionic-angular';
    
    constructor(public toastCtrl: ToastController, public platform: Platform) {
        platform.ready().then(() => {
            //back button handle
            //Registration of push in Android and Windows Phone
            var lastTimeBackPress = 0;
            var timePeriodToExit  = 2000;
    
            platform.registerBackButtonAction(() => {
                // get current active page
                let view = this.nav.getActive();
                if (view.component.name == "TabsPage") {
                    //Double check to exit app
                    if (new Date().getTime() - lastTimeBackPress < timePeriodToExit) {
                        this.platform.exitApp(); //Exit from app
                    } else {
                        let toast = this.toastCtrl.create({
                            message:  'Press back again to exit App?',
                            duration: 3000,
                            position: 'bottom'
                        });
                        toast.present();
                        lastTimeBackPress = new Date().getTime();
                    }
                } else {
                    // go to previous page
                    this.nav.pop({});
                }
            });
        });
    }
    
    0 讨论(0)
  • 2020-12-05 06:48

    Html:

    <button (click)="exitApp()">Close application<button>
    

    TypeScript:

    import {Platform} from 'ionic-angular';
    
    @Page({ /*...*/ })
    export MyPage {
     constructor(platform: Platform) {
      this.platform = platform;
     }
     exitApp(){
      this.platform.exitApp();
     }
    }
    
    0 讨论(0)
  • 2020-12-05 06:52

    Platform api has a handler registerBackButtonAction.

    You can do something like:

    In app.component.ts

        constructor(platform: Platform){
         platform.ready().then(()=>{
           platform.registerBackButtonAction(()=>this.myHandlerFunction());
    })
    
    
      myHandlerFunction(){
        //create alert
         }
    
    0 讨论(0)
  • 2020-12-05 06:54

    This is my resolved and working Code. Thank you everyone.

    constructor(platform: Platform,public alertCtrl: AlertController,public toastCtrl:ToastController) {
        platform.ready().then(()=>{
           platform.registerBackButtonAction(()=>this.myHandlerFunction());
           StatusBar.styleDefault();
          Splashscreen.hide();
    })
      }
    
        myHandlerFunction(){
         let toast = this.toastCtrl.create({
          message: "Press Again to Confirm Exit",
          duration: 3000
        });
        toast.present(); 
         }
    
    0 讨论(0)
提交回复
热议问题