I have a Service from which I am starting AsyncTask from a given timer to do background tasks. My need requires short burst of networking task that's why I am sticking with Asynctask.
From Asynctask I am doing number of operations(such as launching notifications) that requires context. Now, when I am initializing context in my AsyncTask I am getting a warning "This fields leaks a context object."
I have seen number of questions regarding the same but they all were related to Activity/Fragment. So my question is, how can I use context in my AsyncTask(top level class) without leaking it?
You can pass a WeakReference in your AsyncTask, for example :
public class MyAsynctask extends AsyncTask<Void, Void, Void> {
private WeakReference<Context> mWeakContext;
public MyAsynctask (WeakReference<Context> reference) {
mWeakContext = reference;
}
// when you need context use mWeakContext.get();
}
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With