onDestroy of call analysis in Activity Android programming

  • 2020-11-25 07:33:57
  • OfStack

This paper analyzes the onDestroy() call method in Activity programming. To share for your reference, the details are as follows:

Just 1 BUG showed me that if activity implements a callback interface and then USES this to set the method that needs the callback interface, this scenario is quite common. The most common scenario is to implement the onClickListener interface and then findViewById().setOnClickListenr (this).

If the callback interface is set to a static object (singleton mode), when activity finish() (press the back key, go back to the desktop), activity will not be called onDestroy(), possibly because the activity object is still being referenced!

At this point, you click the icon again to go back to the application, and onCreate() is called again!

Obviously, if you release resources into onDestroy(), it will cause a memory leak!

Is there a solution? some

You can determine isFinishing() in the onPause() method. The callback process of activity after the normal call to finish() is onPause, onStop, onDestroy. If the above situation occurs, it only goes to onPause! But the logo for isFinishing() is still true! You can now release resources.

Here's onDestroy's official explanation:


protected void onDestroy () 
Added in API level 1 
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! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away. 
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown. 

I hope this article has been helpful in Android programming.


Related articles: