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?

Oded
  • 489,969
  • 99
  • 883
  • 1,009
Girish
  • 123
  • 1
  • 4
  • 14

1 Answers1

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?

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • 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? – Girish May 05 '11 at 06:19
  • 3
    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. – Ted Hopp May 05 '11 at 06:24
  • another useful way of using onDestroy is, for instance, stopping a Notification Service that is no longer relevant. – aclima Jan 08 '16 at 03:28
  • 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 ? – Shahbaz Hashmi Apr 14 '23 at 14:04
  • @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.) – Ted Hopp Apr 14 '23 at 15:02
  • @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. – Shahbaz Hashmi Apr 14 '23 at 16:21
  • @TedHopp To be more precise it is a Flutter app so my activity extends `FlutterActivity`. – Shahbaz Hashmi Apr 14 '23 at 16:41
  • @ShahbazHashmi - Very odd. I suspect some sort of buffering issue. Try using a different logging technique. See https://stackoverflow.com/q/51007784/535871 and https://stackoverflow.com/q/49940719/535871 for some ideas. – Ted Hopp Apr 14 '23 at 16:47