Is it okay if we override OnDestroy() method in every activity of Android Application?
Asked Answered
C

1

7

Is it okay if we override OnDestroy() method in every activity of Android Application?

@Override
    public void onDestroy() {
        super.onDestroy();
}

Just by calling super.onDestroy() in onDestroy() Method, will it cleanup the memory resources?

Coffin answered 5/5, 2011 at 5:56 Comment(0)
S
15

It's fine to override onDestroy, so long as you do call up to the superclass. If all you're doing is calling up to the superclass, though, why would you do it?

Sofia answered 5/5, 2011 at 6:2 Comment(8)
I would like to cleanup the memory occupied by my application and its activities after closing a particular Activity or navigating the activities. if we call super.onDestroy() in onDestroy() will it clean up the memory resources or do we need to write any code explicitly to clean up the objects?Coffin
You don't need to override onDestroy or do any special cleanup unless you have allocated resources that wouldn't be cleaned up by the Java process going away. Such resources include things like temporary files that would be left on the sdcard.Sofia
another useful way of using onDestroy is, for instance, stopping a Notification Service that is no longer relevant.Kurtkurth
Where should we call the super method when we override onDestroy(). I believe as soon we call the super method, all processes/execution gets terminated. If this is true shouldn’t we call the super at the bottom ?Determinative
@ShahbazHashmi - You can call it anywhere from within your onDestroy() method. The base method does nothing more than set a flag indicating that it has been called. In particular, it does not shut down the process. (Intermediate derived classes may do their own cleanup, but that doesn't change the guidance about writing your own onDestroy() method: call through to the superclass method from anywhere you like that is guaranteed to be executed exactly once.)Sofia
@TedHopp Thanks for the reply, but when I log (override fun onDestroy() { Log.d(TAG, "onDestroy") super.onDestroy() Log.d(TAG, "onDestroy 2") }) then I am able to find "onDestroy" only in the logcat.Determinative
@TedHopp To be more precise it is a Flutter app so my activity extends FlutterActivity.Determinative
@ShahbazHashmi - Very odd. I suspect some sort of buffering issue. Try using a different logging technique. See https://mcmap.net/q/196323/-android-studio-not-showing-logcat-with-flutter/535871 and https://mcmap.net/q/127763/-how-to-log-data-to-the-flutter-console/535871 for some ideas.Sofia

© 2022 - 2024 — McMap. All rights reserved.