Tuesday 30 June 2015

Exit from an ionic app by using hardware back-button

Exit from an ionic app by using hardware back-button:-

For exiting from an ionic app by pressing the hardware back-button, we do the following steps:-

1) Firstly disable the hardware back-button.

 2)Then on HardwareBackButton exit from app.

1) Disable hardware back-button:-



HardwareBackButtonManager Service for Ionic (Angular.js) provides an interface to easily disable the hardware back button on Android



.service( 'HardwareBackButtonManager', function($ionicPlatform){
this.deregister = undefined;
 
this.disable = function(){
this.deregister = $ionicPlatform.registerBackButtonAction(function(e){
e.preventDefault();
return false;
}, 101);
}
return this;
})
 
// usage
.controller( 'YourController', function( 'HardwareBackButtonManager' ){
HardwareBackButtonManager.disable();
})
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

2) On HardwareBackButton exit from app:-

Put the following code accordingly to your angular.run configuration, and that's
it.
.run(function($ionicPlatform, $ionicPopup) {
  $ionicPlatform.onHardwareBackButton(function () {
      if(true) { // your check here
          $ionicPopup.confirm({
            title: 'System warning',
            template: 'are you sure you want to exit?'
          }).then(function(res){
            if( res ){
              navigator.app.exitApp();
            }
          })
      }
  })
});

1 comment:

  1. Thank you so much ma'am for posting these solutions! I'm learning Angular and Ionic and I find your blog very helpful. I had a question regarding other two buttons beside the Back button i,e Home button and the button which switches between multiple apps. How can they be disabled in ionic?

    ReplyDelete