简体   繁体   中英

Device(Android) back button click detection using Ionic2/angular2

I am able to detect the device(Android) back button click event using the following code. But after clicking the back button, it is going one level back and opening the confirmation dialog.

How do i avoid this behavior(going to the previous screen) using ionic2?

registerBackButtonListener() {              
        document.addEventListener('backbutton', () => {           
            let backBtnCnfirm = this.alertCtrl.create({
              message: 'Do you want to close the App?',
              buttons: [
              {
               text: 'Yes',
               handler: () => {
               this.platform.exitApp();
              }
            },
            {
             text: 'No',
             handler: () => {
            }
          }
        ]
       });
        backBtnCnfirm.present();
        }, false);
    }

The back button will call navCtrl.pop() , so going back to the previous page. Ionic offers lifecycle events such as viewDidEnter, viewWillEnter, viewWillLeave etc.

When in your code you create this function:

ionViewWillLeave(){
   this.alertCtrl.create({
     message: 'Do you want to close the App?',
              buttons: [
              {
                text: 'Yes',
                handler: () => {
                  this.platform.exitApp();
               }
             },
             {
              text: 'No',
              role: 'cancel'
            }
           ]
   }).present();
}

Ionic will execute this before the navCtrl.pop() has been executed.

Note: this will execute every time the page will leave (so when pushing or popping manually) but I think you're smart enough to find a workaround (boolean check fe)

(I don't know your requirements but I find it bad UX to show such a message when the backbutton is pressed, usually people would want to go a page back)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM