I read the article How to Leak a Context: Handlers & Inner Classes, and now I have got a question. If I pass mHandler
as a parameter to another thread to send messages from that thread to the main thread, will it cause memory leaks?
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);
}
}