如何泄露上下文。 MyHandler的实例是否会导致泄漏?

时间:2014-09-11 10:22:42

标签: android memory-leaks handler weak-references

我阅读了文章How to Leak a Context: Handlers & Inner Classes,现在我有了一个问题。如果我将mHandler作为参数传递给另一个线程以将消息从该线程发送到主线程,它是否会导致内存泄漏?

SampleActivity

public class SampleActivity extends Activity {

    /**
     * Instances of static inner classes do not hold an implicit reference to
     * their outer class.
     */
    private static class MyHandler extends Handler {
        private final WeakReference<SampleActivity> mActivity;

        public MyHandler(SampleActivity activity) {
            mActivity = new WeakReference<SampleActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            SampleActivity activity = mActivity.get();
            if (activity != null) {
                // ...
            }
        }
    }

    private final MyHandler mHandler = new MyHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Run a thread (authentication, synchronization, etc.)
        // Later the user might press the Home button, the Back button, or make a call
        new MyThread(mHandler).start();
    }
}

MyThread的

public class MyThread extends Thread {

    private final Handler handler;

    public MyThread(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void run() {
        // A long operation

        // I'm done
        handler.sendEmptyMessage(1);
    }

}

2 个答案:

答案 0 :(得分:3)

如果MyThread是静态类或外部类,则不会导致泄漏。对活动没有任何非弱引用。

答案 1 :(得分:2)

看起来不错。我没有看到任何对象持有Activity的链接(WeakRef没关系,因为它可以被GCed)。我没有看到潜在的泄漏;)