How do I kill an Activity when the Back button is pressed?


Question

I got an Activity that when it starts, it loads an image from the internet. In an effort to save memory, when the Activity is left by the back button being pressed, I want the activity to dump all data, that is get rid of all the strings and images that are in it. I figured the best way to do this was to just kill the activity.

Well, I can't seem to figure out the callback for when the Back button is pressed. So, I have been trying to use the onPause() and the onStop() callbacks for the task but both ways force close my app. Here is the code:

public void onPause() {
    this.finish();
}
public void onStop() {
    finish();
}

I've tried multiple variations of this, but none of them seemed to work. Any ideas?

1
31
6/16/2017 9:35:22 PM

Accepted Answer

add this to your activity

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK))
    {
        finish();
    }
    return super.onKeyDown(keyCode, event);
}
39
1/24/2011 5:06:05 AM

Simple Override onBackPressed Method:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon