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?
Well, if you study the structure of how the application life-cycle works,here , then you'll come to know that
onPause()
is called when another activity gains focus, andonStop()
is called when the activity is no longer visible.From what I have learned yet, you can call
finish()
only from the activity which is active and/or has the focus. If you're callingfinish()
from theonPause()
method that means you're calling it when the activity is no longer active. thus an exception is thrown.When you're calling
finish()
fromonStop()
then the activity is being sent to background, thus will no longer be visible, then this exception.When you press the
back
button,onStop()
is called.Most probably, Android will automatically do for you what you are currently wanting to do.
First of all,
finish()
doesn't destroy your process and free up the memory. It just removes the activity from the activity stack. You'd need to kill the process, which is answered in a bunch of questions (since this is being asked several times).But the proper answer is - Don't do it. the Android OS will automatically free up memory when it needs memory. By not freeing up memory, your app will start up faster if the user gets back to it.
Please see here for a great write-up on the topic.
My app closed with above code.
add this to your activity
Simple Override onBackPressed Method: