Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android getApplicationContext memory management

In this post

When to call activity context OR application context?

Mark Murphy says

"It can create memory leaks, if the Context from getApplicationContext() holds onto something created by your calls on it that you don't clean up. With an Activity, if it holds onto something, once the Activity gets garbage collected, everything else flushes out too. The Application object remains for the lifetime of your process."

What calls create something that the application context keeps hold of?

I have a library which needs a context for various things. It can run in the background and spans activities but to use and update activity contexts would be problematic.

I think this is probably one of the occasions where using application context is preferable?

like image 632
Cullan Avatar asked Apr 22 '26 02:04

Cullan


1 Answers

If the lifetime of the objects in the library can span several activities, then absolutely use the applications context. Using the activities context prevents the garbage collector from throwing the context away. Since an activity context can hold on to quite some data, your memory usage can increase drastically.

Also, if an activity is closed it gives up its window token. Trying to spawn a dialog with that context will give a BadTokenException. Thus there is no point to give the activities context to an object, if the object is not directly tied to the activities life cycle.

Edit: Here is a credible source

like image 133
pgsandstrom Avatar answered Apr 25 '26 17:04

pgsandstrom