Android AsyncTask 中的上下文泄漏
如果我正确解释这篇文章,则传递活动AsyncTasks
的上下文是一个潜在的泄漏,因为活动可能会在任务仍在运行时被销毁。
您如何在非内部类且需要访问资源或更新 UI 的 AsyncTasks 中处理此问题?
此外,如果您需要引用进度对话框来关闭它们,如何避免泄漏上下文?
If I interpret this article correctly, passing the activity context to AsyncTasks
is a potential leak, as the activity might be destroyed while the task is still running.
How do you deal with this in AsyncTasks
that are not inner clases and need access to resources or to update the UI?
Additionally, how can you avoid leaking the context if you need references to progress dialogs to dismiss them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我正确理解你的问题:Java 的 WeakReference 或 SoftReference 类非常适合这种情况。它将允许您将上下文传递给 AsyncTask,而不会阻止 GC 在必要时释放上下文。
GC 在收集 WeakReference 时比收集 SoftReference 时更加急切。
而不是:
您的代码将如下所示:
在 AsyncTask 中,而不是:
您的代码将如下所示:
If I understand your question correctly: Java's WeakReference or SoftReference class is a good fit for this type of situation. It will allow you to pass the context to the AsyncTask without preventing the GC from freeing the context if necessary.
The GC is more eager when collecting WeakReferences than it is when collecting SoftReferences.
instead of:
your code would look like:
and in the AsyncTask instead of:
your code would look like: