Android: How To Disable Back Button


In your application you might need to disable back button. Some handle back button operations by providing image/button on screen or by editing back key’s action listener. But if you don’t handle it or disable it User might find closing your application while trying to go back to previous screen.
NOTE: If you want to disable back key in entire application then don’t forget to provide explicit application close button.

Solution:

For the purpose you will need to attach OnKeyListener to your object, for example if you have a dialog, lets say “mainScreen” then:

mainScreen.setOnKeyListener(mainScreenKeyListener);

OnKeyListener mainScreenKeyListener = new OnKeyListener() {

    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {

        boolean disableEvent = false;

        if (event.getKeyCode()==KeyEvent.KEYCODE_BACK) {

            disableEvent = true;

        }

        return disableEvent;
    }
};
/** 
* you can add "event.getAction()==KeyEvent.ACTION_DOWN" 
* to the condition to make it work on ACTION_DOWN specifically 
* or you can look up "KeyEvent" class to enable/disable/modify 
* behavior on various Buttons and Actions.
*/