</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();
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/36511.html