Shekhar Shekhar - 5 months ago 15
Android Question

How to handle back button in activity

How to handle a back button in an activity. Where I have some buttons. If I click one of the button it's redirecting to the buttons which I required. It's working fine but When I press back button it gets finished.

How to solve this problem. I have only one activity for all those buttons.
Thanks in advance.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
return false; //I have tried here true also
}
return super.onKeyDown(keyCode, event);
}


I have used above code to handle back button but its not working. When I press back button its struck there itself.

Answer

You can handle this using: for API level 5

@Override
public void onBackPressed() {
    // your code.
}

and for older then API 5 use this:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // your code
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

Enjoy!!

Comments