Android context leaks in AsyncTask

与世无争的帅哥 提交于 2019-11-29 03:56:06

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:

FooTask myFooTask = new FooTask(myContext);

your code would look like:

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

and in the AsyncTask instead of:

myContext.someMethod();

your code would look like:

myWeakContext.get().someMethod();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!