Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Context Weak Reference

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?

like image 249
Eliezer Avatar asked Oct 23 '13 01:10

Eliezer


Video Answer


2 Answers

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.

like image 169
kabuko Avatar answered Oct 16 '22 20:10

kabuko


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.

like image 24
Joe Plante Avatar answered Oct 16 '22 18:10

Joe Plante