Android : startActivityForResult() with BACK button functionality

Arnab Chakraborty picture Arnab Chakraborty · Aug 3, 2011 · Viewed 8.2k times · Source

I would like to start a new activity for a result, with startActvityForResult(), but I would like to have the back button working as normal in the new activity.

Currently when I invoke a new Activity for result, nothing happens when I press the back button in the new Activity.

I tried something like this:

@Override
public void onBackPressed() {
    setResult(0);
    super.onBackPressed();
    finish();
}

in the new Activity, but it didn't work. Still nothing happens when the back button is pressed.

Is there a way around this?

EDIT : I could of course load the last Activity in the onBackPressed() (can I?), but it seems like a rather crappy hack.

Alex Ady's answer solves my problem, but I still don't understand why onBackPressed() doesn't work. The working code now is something like this:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        setResult(1);
        finish();
    }
    return super.onKeyDown(keyCode, event);
}

I could use an explanation.

Answer

user874649 picture user874649 · Aug 3, 2011

You could try

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
         finish();
    }
    return super.onKeyDown(keyCode, event);
}