Playing with android hardware backbutton

I have a problem in ionic application, When backbutton is pressed the application closes. I used ionic sidemenu in my application.I got a code from ionic forum to prevent hardware back button. But it is too uncomfortable

 $ionicPlatform.onHardwareBackButton(function() {
     event.preventDefault();
     event.stopPropagation();
     alert('going back now y'all');
  });

I want to close the application only on double tap of hardware back button.
When i press backbutton once , a message should appear in bottom of phone like - press again to exit It should close automatically.
I completed my application almost 99% . But my only problem is this backbutton.

How can be it done ?
Pease help.

Thanks.

Hmm, as far as I know, detecting double tap on the back button isn’t possible at the hardware level through Cordova.

However, you can still fake the functionality with $timeout.

Here’s a codepen showing a sort of virtual click. Basically you could use the factory like so:

 $ionicPlatform.onHardwareBackButton(function() {
     if (ClickFactory.simulateClick() == 'single'){
         event.preventDefault();
         event.stopPropagation();
         // display some message
      } else {
         alert('going back now y'all');
      }
});
1 Like
$rootScope.sequentialBackButtonPresses = 0;
$ionicPlatform.onHardwareBackButton(function() {
     event.preventDefault();
     event.stopPropagation();
     if( $rootScope.sequentialBackButtonPresses == 1 ) {
         alert('Closing application');
        $rootScope.sequentialBackButtonPresses = 0;
     } else {
        alert('Press again to close application');
        $rootScope.sequentialBackButtonPresses++;
    }
});

In your HTML you could do:

<div data-ng-show="($root.sequentialBackButtonPresses == 1)">Press again to close application</div>

Of course you would have to provide decent positioning and css to mmake the message appear at the place where you want it :smile:

Let me know if this helped.

2 Likes