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

Shaun picture Shaun · Jan 24, 2011 · Viewed 134.9k times · Source

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?

Answer

Dhiral Pandya picture Dhiral Pandya · Feb 29, 2012

Simple Override onBackPressed Method:

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