直接上代码,使用两种办法
1,静态内部类
/**
* 声明一个静态的Handler内部类,并持有外部类的弱引用
*/
private static class MyHandler extends Handler{
private final WeakReference<ServerActivity> mActivty;
private MyHandler(ServerActivity mActivty) {
this.mActivty = new WeakReference<ServerActivity>(mActivty);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
ServerActivity activity = mActivty.get();
if (activity != null){
//注意,这里的test,btn_closeServer都是成员变量
activity.test ="hello";
activity.btn_closeServer.setText(" 小样,你好吗");
}
}
}
2,
在activity 的ondestory()的时候,
调用mHandler.removeCallbacksAndMessages(null);