Activity isFinishing of Judge the status instance of Activity

  • 2021-08-28 21:18:02
  • OfStack

When calling finish () in Activity or pressing the return key to exit, activity will not be called the onDestory () method if a resource is referenced by another object and cannot be released (for example, context is referenced by a singleton object or is being used in a thread).

isFinishing () can be used to determine whether Activity is active (false) or waiting for recovery (true).

isDestroyed () According to the source code comments, it returns true only after the onDestroy () method is called, so it is of little practical use.

View the comments in the source code:


/**
 * Check to see whether this activity is in the process of finishing,
 * either because you called {@link #finish} on it or someone else
 * has requested that it finished. This is often used in
 * {@link #onPause} to determine whether the activity is simply pausing or
 * completely finishing.
 *
 * @return If the activity is finishing, returns true; else returns false.
 *
 * @see #finish
 */
public boolean isFinishing() {
 return mFinished;
}
/**
 * Returns true if the final {@link #onDestroy()} call has been made
 * on the Activity, so this instance is now dead.
 */
public boolean isDestroyed() {
 return mDestroyed;
}

Research on Activity onDestroy () Call

Just one BUG made me find that if activity implements a callback interface and then uses this to set up a method that needs a callback interface, this application scenario is more common. The most common one is to implement onClickListener interface and then findViewById (). setOnClickListenr (this)

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

At this time, you click the icon again to return to the application, and onCreate () is called again!

Obviously, if you put the resource release in onDestroy (), it will lead to a memory leak!

Is there a solution?

Some you can judge isFinishing () in onPause () method. After calling finish () normally, the callback process of activity is onPause, onStop and onDestroy. If the above situation occurs, only onPause! But the isFinishing () flag is still true! You can release resources.


Related articles: