AsyncTask 中的 Android 上下文泄漏 [英] Android context leaks in AsyncTask

查看:33
本文介绍了AsyncTask 中的 Android 上下文泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我正确解释了这篇文章,将活动上下文传递给 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.

你如何在 AsyncTasks 中处理这个不是内部类并且需要访问资源或更新 UI 的?

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?

推荐答案

如果我正确理解您的问题:Java 的 WeakReference 或 SoftReference 类非常适合这种情况.它将允许您将上下文传递给 AsyncTask,而无需阻止 GC 在必要时释放上下文.

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.

收集 WeakReferences 时 GC 比收集 SoftReferences 时更急切.

The GC is more eager when collecting WeakReferences than it is when collecting SoftReferences.

代替:

FooTask myFooTask = new FooTask(myContext);

您的代码如下所示:

WeakReference<MyContextClass> myWeakContext = new WeakReference<MyContextClass>(myContext);
FooTask myFooTask = new FooTask(myWeakContext);

并在 AsyncTask 中代替:

and in the AsyncTask instead of:

myContext.someMethod();

您的代码如下所示:

myWeakContext.get().someMethod();

这篇关于AsyncTask 中的 Android 上下文泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆