Android context leaks in AsyncTask

前端 未结 1 1490
灰色年华
灰色年华 2020-12-16 18:12

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 stil

相关标签:
1条回答
  • 2020-12-16 18:28

    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();
    
    0 讨论(0)
提交回复
热议问题