0
votes

I am trying to prevent the android back button from going back on a certain page of my application. Everywhere online suggest the code below, however it is not working. I put a breakpoint in the 'backbutton' event listener, it hits it just fine. However the app still goes back a page.

I am using Ionic on top of Cordova(4.0.0). I am testing it using an Android(4.4.2) emulator.

Any Thoughts?

Here is the code I am using.

document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
    document.addEventListener("backbutton", function (e) {
        e.preventDefault();
    }, false );
}
2
did you try using onBackPressed() in your activity?Silvia H

2 Answers

0
votes

I found a post related to same in Iconic forum.

A sample script :

$ionicPlatform.registerBackButtonAction(function () {
  //handle back action
}, 100);

P.S: You can also disable the backButton function as mentioned in this answer .

0
votes

Put this in your Father Activity

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {

        if (!sharedPreferences.isBackButtonEnabled()) { // Save a flag in sharedPreferences to know when you have button enable or not. 
            return true;
        }

    }

    return super.onKeyDown(keyCode, event);
}

And then, in the fragment you want to block the back button:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    sharedPreferences.setBackButtonEnabled(false);
 }

And if you want to enable it when you live that fragment:

@Override
protected void onDestroy() {
    sharedPreferences.setBackButtonEnabled(true);
 }