Search code examples
javaandroidmemory-leaksandroid-asynctask

Passing context from Service to Asynctask without leaking it


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?


Solution

  • I have a Service from which I am starting AsyncTask from a given timer to do background tasks.

    Don't use an AsyncTask. Use a thread. Or, better yet, used ScheduledExecutorService 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.

    So my question is, how can I use context in my AsyncTask(top level class) without leaking it?

    Call getApplicationContext() on the Service and use that Context.