Is it safe to store the Android Application Contex...
# android
s
Is it safe to store the Android Application Context in a static variable? Every time I make a library that does this, I get a warning that it's not safe, causes memory leaks, and would break instant run. As long as this is done with an Application Context, I can't think of a reason this wouldn't be ok. Can anyone argue otherwise?
stackoverflow 2
v
Really interested... I could not find any relevant information in the web
s
I can't think of any reason that as long as I hold onto the
Application
context, and not an Activity context, that I'm causing a memory leak. It's possible I mess with instant run, although I don't see how it would, but I'm not entirely sure how Instant Run works, so maybe. Instead of storing the variable as a
Context
, I'm casting it to
Application
instead, and the warning went away. Either its an oversight by the Android team, or storing the Application context is in fact fine.
i
Answer is NO.
s
@itnoles care to elaborate?
i
static treats like immutable copy. When Android decided to restart that activity, that static one will be like danging pointers which causes memory leak.
s
Right, but that's my point. I'd be storing the Application context, not an Activity context. Since the application is a singleton, it should theoretically be ok
s
Don store as Context. If field is context and you set application. That is something you know not lint. Context means it can be activity as well. Be more specific about what you hold when you work with context.
m
@Sinan Kozak you mean storing static
Application
is good, but static
Context
is bad?
s
I mean storing any kind of context is bad. But for that lint check, static context is wrong. My suggestion pass context as method parameter when you need it. I dont think you need to store as static.
1
s
I'm creating a multiplatform library. In many cases it becomes very difficult to get a context to a certain place.
c
The lint check is a matter of where the static Application instance is held. It’s trying to be overly cautious to remind you to be careful (something like statically referencing ANY context in an Activity/Fragment/View is wrong), but you are correct that if you are careful (e.g. statically referencing anything in your Application class) there is nothing wrong. That said, do be careful. Using something like Dagger/DI/Service Locator makes it easier to do the right thing here. Only need to store the Graph as a static variable, and everything in the root scope will be implicitly statically accessible.
Minimizing the number of things that are static to one static graph instance (i.e. one Dagger root component) makes it possible to avoid storing anything else as static
189 Views