首页 > 解决方案 > 在 WeakReference 上调用 clear() 不起作用

问题描述

我在我的 Activity 中使用嵌套的私有静态 AsyncTask 类来做一些工作,我将 Activity 上下文传递给 AsyncTask 并将其初始化为 WeakReference。
在我的工作完成后onPostExecute(),我正在打电话
if(mContext.get() != null) mContext.clear();

但是当我检查 logcat 是否时mContext != null,它总是返回true

标签: androidandroid-asynctask

解决方案


mContext == null我查看了一些文章和其他一些 stackoverflow 答案,我得出的结论是,除非您分配 null 或活动正在完成或在异步任务完成工作之前已被破坏,否则您不会得到。

因此,当您使用mContext.clear();时,不要mContext设为 null,您只需清除此引用对象并调用它不会导致该对象排队等待 GC。因此,只有mContext.get() == null在清除以下引用后,您才会得到 true。

@Override
        protected void onPostExecute(Object object) {
            super.onPostExecute(object);
            if (mContext.get() != null) {
                mContext.clear();
            }

            Log.d("MG-Context", mContext.get() == null ? "Yes" : "No");
        } 

请在此处查看本文以获得更好的信息: https ://medium.com/google-developer-experts/finally-understanding-how-references-work-in-android-and-java-26a0d9c92f83


推荐阅读