Search code examples
androidangularjscordovaionic-frameworkback-button

Exit application from android hardware back button in phonegap


Is there a way to show a confirmation popup when you press the hardware back button in android devices to exit the phonegap/ionic application?

In the current status, my app keep going to the previous state upon clicking the back button.

Is there a way to exit the app when you press the back button no matter where you are on, in the application?

I found this piece of code but it did not seem to work:

$ionicPlatform.registerBackButtonAction(function() {
    var confirmPopup = $ionicPopup.confirm({
        title: 'Sign Out Confirm',
        template: 'Are you sure you want to Logout?'
    });
    confirmPopup.then(function(res) {
        if (res) {
            $rootScope.rootScopeUserTransactionPassword = null;
            $state.go('app.playlists');
        } else {
            console.log('You are not sure');
        }
    });
}, 100);

Solution

  • Try this:

    document.addEventListener('backbutton', function(event){
      event.preventDefault(); // EDIT
      navigator.app.exitApp(); // exit the app
    });
    

    I hope it helps you.