在AsyncTask的Andr​​oid的情况下泄露 [英] Android context leaks in AsyncTask

查看:142
本文介绍了在AsyncTask的Andr​​oid的情况下泄露的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我跨preT这文章正确,传递活动上下文 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 不属于内部clases和需要访问资源或更新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的无$ P $从如有必要释放的背景下pventing的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收集比时,它正在收集SoftReferences当GC更加渴望。

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

来代替:

FooTask myFooTask = new FooTask(myContext);

您code看起来像:

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

和在AsyncTask的,而不是:

and in the AsyncTask instead of:

myContext.someMethod();

您code看起来像:

myWeakContext.get().someMethod();

这篇关于在AsyncTask的Andr​​oid的情况下泄露的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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