gpt4 book ai didi

android - 如何泄漏上下文。 MyHandler 的实例会导致泄漏吗?

转载 作者:行者123 更新时间:2023-11-29 15:14:42 25 4
gpt4 key购买 nike

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

示例 Activity

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();
}
}

我的线程

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);
}

}

最佳答案

如果 MyThread 是静态类或外部类,则不会造成泄漏。没有对 Activity 的任何非弱引用。

关于android - 如何泄漏上下文。 MyHandler 的实例会导致泄漏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25784974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com