According to the internet it is really easy to change the behaviour of the standard Android back button:

public void onBackPressed() {
   // Your code goes here.
   return;
}

This is documented of course and all fine and happy.

Except it didn’t work for me. This is because it was introduced in Android 2.0, and I’m developing for 1.5 and above. Sad, I know :P

The sollution isn’t all that hard: Just override the keypress, filter out the backbutton, and call the parent function for the rest. Easy as that.

public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK
        && event.getRepeatCount() == 0) {
        //Your code goes here.
        return true;
    }
    //call parent function for other keys
    return super.onKeyDown(keyCode, event);
}

This seems reasonably forward enough, and doesn’t seem to be too breakable in future updates.

2 comments on Change android back-button in 1.5

  1. aoeu says:

    did google bother to leave up a 1.5 api reference, or did they assume that as soon as a new api level came out that everyone would throw away their phones and get ones that supported it?

  2. ennaN says:

    The biggest problem with this example is that there was no functionality in 1.5 to actually do this. Above is just a general way to handle keypresses, specialised for the ‘back’ key.
    My biggest problem here was that because the newer versions DO have a special way to handle backkey pressing, my first try of implementing this (“lets just google it”) ended up with all sorts of “thats really easy, do this!” mentions of above 2.0 function.

    The general eventhandling of keys and the ‘code’ for the back-key is in the docs, but you have to ignore all the 2.0 hints of other people :)