尽管仍然显示Activity,但AsyncTask中的WeakReference无效

时间:2019-03-19 08:40:03

标签: android android-asynctask weak-references

我通过在构造函数中分配一个弱引用来遵循在AsyncTask中使用WeakReference的模式:

private final WeakReference<WeakClass> weakRef;

public WeakRefAsyncTask( @NotNull WeakClass _weakClassInstance ) {

    weakRef = new WeakReference<>( _weakClassInstance );
}

protected final @NonNull WeakClass getWeakOne() {

    WeakClass o = weakRef.get();

    if( o != null ) {

        return o;
    } else {

        throw new WeakRefIsNullException( getTaskDetailsDescription() );
    }
}

但是现在我遇到另一个问题-即使活动仍在进行中,弱引用也会一次无效(DoWeaklyAsyncTask是AbstractPurchaseListActivity中WeakRefAsyncTask的静态内部后代)。

03-19 11:02:19.632 5184-5305/com.tsarsprocket.purchaselist.subscribe E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #5
Process: com.tsarsprocket.purchaselist.subscribe, PID: 5184
java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:300)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)
 Caused by: com.tsarsprocket.DroidTools2.tools.WeakRefAsyncTask$WeakRefIsNullException: Weak reference is null. Task details:
Loading names already used in purchase list version, id=-1
    at com.tsarsprocket.DroidTools2.tools.WeakRefAsyncTask.getWeakOne(WeakRefAsyncTask.java:37)
    at com.tsarsprocket.purchaselist.core.AbstractPurchaseListActivity$DoWeaklyAsyncTask.doWeakInBackground(AbstractPurchaseListActivity.java:225)
    at com.tsarsprocket.DroidTools2.tools.WeakRefAsyncTask.doInBackground(WeakRefAsyncTask.java:118)
    at android.os.AsyncTask$2.call(AsyncTask.java:288)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        ... 4 more

问题在于,当弱引用被取消时,活动仍然是实际的,并且仍然需要acynctask的结果。我怀疑这可能是因为积极的GC。而且该任务无法告诉活动它失败,因为弱引用是唯一的链接。

请问有什么方法可以有效地在asynctasks中使用weakrefs,并防止asynctasks因weakref无效而失败?

0 个答案:

没有答案