Android Context Weak Reference

In some of my applications, I use several singleton objects as "managers". I create them in Application.onCreate and pass them the ApplicationContext , which I store in WeakReference .

Some of the "manager" methods start a background task after a call from Activity , so I pass the Activity context method to the method and save the WeakReference in it (and use what's inside AsyncTask ). This link remains until the next time the Activity calls a method that goes into the background when the WeakReference set to a new Activity context .

My question is, should the ApplicationContext be stored in WeakReference , and are there any problems with maintaining the Activity context ?

+6
android android-context android-asynctask android-memory
Oct 23 '13 at 1:23
source share
2 answers

The reason for maintaining the WeakReference the activity context is that you will not continue to reference the Activity that was or should be otherwise destroyed. There is no such problem for Application . A WeakReference is not required in this case.

It is impossible to comment on your use of the activity context, since you did not indicate what exactly you are using it. It sounds a little suspicious that you are changing context for different actions. If you really need a specific activity context, this might be fine, but if you just want to use a valid Context for use with AsyncTask , I would consider rethinking your approach. This will probably work, but it is a bit hacked. There are other options that may be more appropriate depending on your needs: IntentService and Loaders are options to consider.

+9
Oct 23 '13 at 1:49 on
source share
— -

In general, you do not need to maintain the application context in WeakReference mode. However, you must save other types of contexts in WeakReference.

+5
Sep 30 '14 at 22:36
source share



All Articles