简体   繁体   中英

Android onDestroy() method not working as expected

I use onDestroy() method, and my code is not completed:

    @Override
    public void onDestroy() {
        super.onDestroy();
        for (int i = 0 ; i < 10; i++) {
            Toast.makeText(this, "Destroy " + i, Toast.LENGTH_SHORT).show();
        }
    }

The for loop stops at index 2. Why does the loop not end?

First of all the documentation says that the onDestroy() method:

should not be used to do things that are intended to remain around after the process goes away.

and:

This method is usually implemented to free resources like threads that are associated with an activity

Also at the beginning of the docs on the Activity there is a note that the methods onDestroy() and onStop() are killable :

methods that are marked as being killable, after that method returns the process hosting the activity may be killed by the system at any time without another line of its code being executed.

And there is a recommendation to use the onPause() method instead of those that are killable.

So apparently there is some android internal timeout for the onDestroy() function that might be controlling if nothing too long is happening in it and if it does, then it probably kills the execution. This is my guess.

Based on what was in the documentation I would refrain from using this method to do what You are doing here and I would try using the onPause() method instead.

If the code is meant to be executed only when the applicatoin is finishing then use the isFinishing() method to check for it. The docs recommend this approach:

Check to see whether this activity is in the process of finishing, either because you called finish() on it or someone else has requested that it finished. This is often used in onPause() to determine whether the activity is simply pausing or completely finishing.

@sweak's answer pretty much explains why you should not do this. But if you are keen to do it. You can do like below it will complete the for loop and give the output of all 10 toasts.

@Override
    public void onDestroy() {
        for (int i = 0 ; i < 10; i++) {
            Toast.makeText(this, "Destroy " + i, Toast.LENGTH_SHORT).show();
        }
        super.onDestroy();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM