Android Context Weak Reference
Asked Answered
S

2

7

In some of my apps I use a few singleton objects as "managers." I instantiate them in Application.onCreate and I pass them the ApplicationContext, which I store in a WeakReference.

Some of the "manager's" methods start a background task after being called from an Activity, so I pass the Activity's context to the method, and keep a WeakReference to that as well (and use that inside of an AsyncTask). That reference is kept until the next time an Activity calls a method that goes to the background, when the WeakReference is set to the new Activity's context.

My question is, does the ApplicationContext have to be kept in a WeakReference, and are there any problems with keeping the Activity's context like that?

Scissor answered 23/10, 2013 at 1:23 Comment(0)
D
10

The reason for keeping a WeakReference to the activity's context is so that you won't keep a reference to an Activity that has been or otherwise should be destroyed already. No such issue exists for the Application. A WeakReference is unnecessary in that case.

It's hard to comment on your use of the activity's context since you haven't detailed what you're using it for exactly. It sounds a little suspicious that you're swapping out the context for different activities. If you really need a specific activity's context, this might be ok, but if you simply want a valid Context to use with an AsyncTask then I'd consider rethinking your approach. It'll probably work, but it's a bit hacky. There are other options that may be more appropriate depending on your needs: IntentService and Loaders are options to consider.

Dimple answered 23/10, 2013 at 1:49 Comment(2)
I'm under the impression that you must use an Activity's context in an AsyncTask. Am I mistaken? Are there any situation where ApplicationContext can't be used? If there aren't, I'd much rather switch to using ApplicationContext (would make my life easier).Scissor
Just an addition to above, from what I know an ApplicationContext shouldn't be used when instantiating a View. Is that correct?Scissor
D
5

In general, you do not have to keep the application context in a WeakReference. You should keep other kinds of Contexts in a WeakReference, though.

Diastasis answered 30/9, 2014 at 22:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.