Passing context from Service to Asynctask without leaking it(将上下文从服务传递到异步任务而不泄漏)
问题描述
我有一个 Service
,我从给定的计时器启动 AsyncTask
来执行后台任务.我的需求需要短时间的网络任务,这就是为什么我坚持使用 Asynctask
.
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
.
来自 Asynctask
我正在做一些需要 context
的操作(例如启动通知).现在,当我在 AsyncTask
中初始化 context
时,我收到一个警告这个字段泄漏了一个上下文对象."
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."
我已经看到许多关于相同的问题,但它们都与 Activity/Fragment
相关.所以我的问题是,如何在我的 AsyncTask
(顶级类)使用 context
而不泄漏它?
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?
推荐答案
我有一个服务,我从一个给定的计时器启动 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
.
Call getApplicationContext()
on the Service
and use that Context
.
这篇关于将上下文从服务传递到异步任务而不泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将上下文从服务传递到异步任务而不泄漏


基础教程推荐
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01