Hi everyone. Apologies for the radio silence. I've been a bit busy trying to get a new job - a feat that has been made trickier by the refusal of companies to offer any positions with remote working. So just a quickie today.

One thing that caused a "woah" moment for me when learning Android is when I thought of an Activity as a Java object and not as an Activity. It's too easy to forget that fact because of how special an Activity is, and the fact that you don't create an Activity with a call to new().

What I found is that I was thinking that the Activity stopped doing anything after a call to onPause() had happened (except other lifecycle calls, such as onResume() or onStop(), etc.) But when I thought of an Activity as an object I realised that this is not the case.

Your methods of an Activity can be called after onPause(), even after onStop(). Just because the system has decided that your Activity isn't doing anything doesn't mean the Activity object someone gets frozen.

This can be the source of memory leaks, where some other object contains a reference to your Activity in order to call a method on it later. That means that, even though the system may consider your Activity to have been destroyed (i.e. onDestroy() has been called), the object can't be garbage collected, thus that bit of memory is never freed up.

It can also be the cause of odd behaviour. An example might be if you use an AsyncTask that does a callback to a method on your Activity. If the user goes to another Activity whilst your AsyncTask is still executing, when it has completed the method can still get called on your Activity, even if it is paused or stopped.

So remember to treat your Activities as objects.

Darren @ Æ


comments powered by Disqus