android - 为了在静态内部类中引用我的自定义 View ,WeakReference 是一个好的类型吗?

标签 android weak-references

我正在通过直接继承 View 类来编写自定义 View ,我想知道我是否很好地利用了 WeakReference 类。首先,这是我类(class)中最相关的部分:

public class ChessView extends View {

    public ChessView(Context context, AttributeSet attrs, int defStyle) {
        /* some code removed */
        invalidateHandler = new InvalidateHandler(this);

        new Thread(new Runnable() {

            @Override
            public void run() {
                     invalidateHandler.sendMessage(invalidateHandler.obtainMessage());
        }

        }).start();
    }

    /* some code removed */

    private static class InvalidateHandler extends Handler {

        public InvalidateHandler(ChessView view){
            relatedChessView = new WeakReference<ChessView>(view);
        }

        @Override
        public void handleMessage(Message msg) {
            relatedChessView.get().invalidate();
        }

        private WeakReference<ChessView> relatedChessView; 
    };

    private InvalidateHandler invalidateHandler;

}

如你所见:

  1. 我正在创建一个静态内部类,它是 Handler 类的子类:正如 android 开发人员指南所建议的那样,避免在 View 子类中直接使用内部类
  2. Handler 静态内部类调用我的自定义 ChessView 的 invalidate() 方法:因此我决定将其“包装”在 WeakReference 中,因为 android 开发者指南建议避免对 View 实例进行硬引用。<

所以这是我的问题:

  1. 我可以通过这种方式避免内存泄漏吗?
  2. WeakReference 是最好的类型吗,还是我应该改用 SoftReference?
  3. 最后,只要 View 可见(或相关 Activity 处于 Activity 状态),自定义 View 是否会保留在堆上,或者它是否可能之前被 GC 收集,让我在调用 relatedChessView.get( )?

提前致谢,如果我的问题表述不当,我们深表歉意。

最佳答案

Do I avoid memory leaks this way ?

是的,但这不是必需的。

Is WeakReference the best type, or should I use a SoftReference instead ?

WeakReference 是适合您的情况。 SoftReferenceWeakReference 都可用,只要有硬引用指向它们。如果没有强引用,WeakReference 将更有可能被收集,而 SoftReference 将保留您的对象,只要不需要清理内存(例如。SoftReference 会停留更长时间)。

And finally, will the custom view remains on the heap as long as the view is visible (or the related activity active) or may it be collected by the GC before, letting me with a null reference when calling relatedChessView.get()?

是的,会的。正如我上面提到的,当有任何 Objects 持有包含的 Object 的引用时,将不会收集 WeakReference

更新:根据@DeeV 的回答修复了有关弱引用和软引用的信息,使其更加准确。

关于android - 为了在静态内部类中引用我的自定义 View ,WeakReference 是一个好的类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11900790/

相关文章:

c# - 函数返回时出现 NullReferenceException

android - "Minimize"Android 中的一个 Activity (不要完成)

android - 我可以使用相同的“radioButton_states”drawable 并创建一个每个按钮具有不同背景颜色的 radioGroup 吗?

swift - 为什么在复制实例变量时得到 "Attempted to unregister unknown __weak variable"?

ios - 在 block 、核心数据、swift中使用弱、强的 self 使用

java - 迭代 WeakHashMap

android - 图像拖放

android - ContentUri 的 id 格式为字符串

android - Phonegap 3 自定义插件不工作

Java 8 lambda 弱引用