从服务传递上下文到AsyncTask而不泄漏它 [英] Passing context from Service to AsyncTask without leaking it
问题描述
我有一个Service
,我正在从一个给定的计时器启动一个AsyncTask
来执行后台任务.我的需求需要短暂的网络任务,因此这就是我坚持使用AsyncTask
的原因.
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
.
在AsyncTask
中,我正在执行许多需要Context
的操作(例如启动通知).现在,当我在AsyncTask
中初始化Context
时,我收到一条警告"此字段泄漏了上下文对象."
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."
我已经看到许多关于同一问题,但它们都与Activity/Fragment
有关.所以我的问题是,如何在AsyncTask
(顶级课程)中使用Context
而不会泄漏?
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?
推荐答案
我有一个服务,可以从该服务从给定的计时器启动AsyncTask来执行后台任务.
I have a Service from which I am starting AsyncTask from a given timer to do background tasks.
请勿使用AsyncTask
.使用线程.或者更好的是,将ScheduledExecutorService
用作计时组件,因为它将在后台线程上执行任务. AsyncTask
仅 适用于在后台部分完成后需要在主应用程序线程上进行工作的情况,而服务很少需要这样做.
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.
所以我的问题是,如何在我的AsyncTask(顶级类)中使用上下文而不泄漏它?
So my question is, how can I use context in my AsyncTask(top level class) without leaking it?
在Service
上调用getApplicationContext()
并使用该Context
.
这篇关于从服务传递上下文到AsyncTask而不泄漏它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!