I have a Service
from which I am starting an AsyncTask
from a given timer to do background tasks. My need requires short bursts of networking tasks so that's why I am sticking with AsyncTask
.
From AsyncTask
, I am doing a number of operations (such as launching notifications) that require Context
. Now, when I am initializing Context
in my AsyncTask
, I am getting a warning "This fields leaks a context object."
I have seen a 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 :
Hope this helps.
You can try using a
WeakReference
and a static inner class for yourAsyncTask
to the object you are trying to access. Something like this:Don't use an
AsyncTask
. Use a thread. Or, better yet, usedScheduledExecutorService
for the timing component, as that will execute tasks on a background thread.AsyncTask
is only appropriate for when you need to do work on the main application thread when the background part is done, and that's rarely required with a service.Also, bear in mind that your timer will stop working once your process terminates.
Call
getApplicationContext()
on theService
and use thatContext
.