activity onStop() and destroying process

Viewed 146

I doubt in the meaning of this part of android "Activity lifecycle" tutorial:

It is also important that you use onStop() to release resources that might leak memory, because it is possible for the system to kill the process hosting your activity without calling the activity's final onDestroy() callback.

As I understand, when process is killed all memory associated with it is deallocated. A leak is a situation when a component with greater scope owns a reference to a component with a smaller scope (static reference to a context, handler, inner class etc). But if a process is dead, there are no components alive at all. Yes, some of them can be recreated later, but they will not hold a reference to some "old" components from past. Can anyone give an example of the scenario when killing a process can lead to memory leaks? Or am I totally wrong in my (some of my) assumptions?

Thanks in advance!

2 Answers

Look, If you aren't using onStop() then memory leakage of static variable or reference are leaked. Because, they aren't destroyed until onDestroy() is called. Some of examples are-

1: Stop/close any services/files/connections that you no longer need.

2: Do NOT store any Drawable in any static Object, Drawables hold references to their owner View's which hold references to their owner Activity's, so if you hold on to any Drawable you will hold onto a lot of objects/memory unnecessarily

So, you should always close the connection or set initialisation to null of static views in onStop() to prevent memory leakage. Hope it clears :)

The wording in the documentation is not good. When your OS process is killed, all memory is reclaimed. There are no memory leaks possible in this case.

Related