Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onDestroy() gets called when the back button is pressed

In my Activity, I have overrode onDestory() and just put a log call to show if this method is being called. (tested on Android 4.2.2 and 4.4.4)

@Override
protected void onDestroy() {
    Log.i(TAG, "onDestroy() was called");
    super.onDestroy();
}

When I press the back button, this method gets called (I saw the log).

I believe this should not happen unless phone gets low in memory or something. I have nothing much in the app but the MainActivity and some fragments.

Here is the log when the user is in the MainActivity and presses the back button:

I/MainActivity? onBackPressed() was called
I/MainActivity? onStop() was called
I/MainActivity? onDestroy() was called

Why this happens?

I also checked for isFinishing() in the onPause() and it always returns true

From the Javadoc :

Perform any final cleanup before an activity is destroyed. This can happen either because the activity is finishing (someone called finish on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing method. Note: do not count on this method being called as a place for saving data!

like image 831
Saeid Yazdani Avatar asked Jul 30 '14 01:07

Saeid Yazdani


1 Answers

When you press back button inside an Activity, it will call finish(), which will "close" it.

Activity.java

/**
 * Called when the activity has detected the user's press of the back
 * key. The default implementation simply finishes the current activity,
 * but you can override this to do whatever you want.
 */
public void onBackPressed() {
    if (!mFragments.popBackStackImmediate()) {
        finish();
    }
}

When it happens, onDestroy() can (and usually will) be called.

protected void onDestroy ()

Perform any final cleanup before an activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.

The same reason also goes to why putting isFinishing() inside onPause() always returns true, if you press the back button (call finish()). It will not return true if you hide the Activity with other method, e.g. pressing the home button.

like image 113
Andrew T. Avatar answered Sep 22 '22 10:09

Andrew T.