Application scenarios

In a real project, after the network data is returned asynchronously, the View data needs to be populated in the UI thread. I used it at first! IsFinishing () to determine if the Activity is alive and if it is not destroyed, the populate data method is executed. However, there are occasional sporadic crashes on Bugly, reporting View’s NPE. Therefore, isFinishing() does not tell if the Activity was destroyed under certain circumstances.

Correct judgment condition

/** * Whether the Activity was destroyed * @return
 */
public boolean isActivityEnable() {if(this == null || isDestroyed() || isFinishing()){
        return false;
    }
    return true;
}Copy the code

Fragments of

public boolean isActivityEnable() {returngetActivity()! =null && ! getActivity().isDestroyed() && ! getActivity().isFinishing()&& isAdded(); }Copy the code

Question why

IsFinishing () returns mFinished. MFinished is assigned in Finish (), which means that the value of mFinished will only be set to true if the Activity is terminated by calling Finish (). So sometimes the Activity life cycle doesn’t work as expected (for example, when memory is tight), and judgment errors can occur.