3

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?

Community
  • 1
  • 1
Cullan
  • 1,198
  • 10
  • 14

2 Answers2

1

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

pgsandstrom
  • 14,361
  • 13
  • 70
  • 104
  • This was the reason I was thinking about using getApplicationContext, much easier to control rather than managing the contexts across activities but really would like to now how (if?) it would be possible to leak memory in the scenario of the application context? – Cullan Jun 27 '12 at 13:04
  • The only extra risk would be if the library somehow depends on the context being invalidated at some point, or if there is an error in the library that makes it stay in memory for the lifetime of the context. – pgsandstrom Jun 27 '12 at 13:19
  • Allow me to clarify: It is possible for the library to make the context reference it. If it does that, then it will stay in memory as long as the context. However, this would be very bad design on the part of the library. – pgsandstrom Jun 27 '12 at 13:23
0

I face the same issue during one of my library projects.

Its recommended to use Activity Contexts even in library projects. There are lot of components which require activity context only. For ex : Dialogs. Therfore my suggestion is to pass activity context from your project to library project.

Although Application contexts can save serialization issue in library projects.

vineet
  • 269
  • 1
  • 4
  • 18