Sounds to me like a memory leak. Always use WeakReferences
in AsyncTasks
when passing a Context
or Activity
or other such objects to it. Try something like this:
public class ExampleAsyncTask extends AsyncTask<Void, Void, Boolean> {
private final WeakReference<Context> contextReference;
public ExampleAsyncTask(Context context) {
this.contextReference = new WeakReference<Context>(context);
}
@Override
protected Boolean doInBackground(Void... params) {
Context context = this.contextReference.get();
if(context != null) {
// Do your work
}
return false;
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
Context context = this.contextReference.get();
if(context != null) {
// Do your work
}
}
}
What the WeakReference
does is to allow for the object it is referencing to be garbage collected. If you hold the reference directly the object cannot be garbage collected and this can cause memory leaks in Threads
and AsyncTasks
. This would for example happen when you hold a Context
reference directly and the Activity
from which the Context
object comes is recreated, for example when you rotate your device or the Activity
is in the background for some time.
In the example above you save the Context
object in a WeakReference
, and every time you want to use the Context
you first have to get it from the WeakReference
. After you got it from the WeakReference
you can simply check if it is null or not. If it is not null than it is safe to work with the Context
. If it is null than the Context
or the corresponding Activity
have already been garbage collected and are not usable anymore.