</pre><pre name="code" class="java">在Activity中可通过WeakReference来是用Handler,可以有效防止内存泄露。
</pre><pre name="code" class="java">public class HandlerActivity extends Activity {
private String string = "string";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
myHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
public void test(){
System.out.println("test");
}
MyHandler myHandler = new MyHandler(this);
static class MyHandler extends Handler{
private WeakReference<HandlerActivity> weakReference;
public MyHandler(HandlerActivity handlerActivity) {
this.weakReference = new WeakReference<HandlerActivity>(handlerActivity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
HandlerActivity activity = weakReference.get();
// 调用HandlerActivity中的变量
System.out.println(activity.string);
// 调用HandlerActivity中的方法
activity.test();
}
}
}