我正在修改我的活动中的以下代码:
new Handler().postDelayed(new Runnable() {
public void run() {
txtStatus.setText("hello");
}
}, 1000);
为:
static Runnable myRunnable = new Runnable() {
public void run() {
txtStatus.setText("hello");
};
new Handler().postDelayed(myRunnable, 1000);
这显然不起作用,因为我们引用的是非静态变量。
这也不起作用:
public void setText() {
txtStatus.setText("hello");
}
static Runnable myRunnable = new Runnable() {
public void run() {
setText(); // doesn't work
MyActivity.this.setText(); // still doesn't work
};
new Handler().postDelayed(myRunnable, 1000);
那么我的初始示例如何被重写为使用静态类而不是匿名内部类(以避免内存泄漏的可能性)?
答案 0 :(得分:5)
您可以使用WeakReference来避免内存泄漏问题。这是一些代码,它说明了这个想法
public static class MyRunnable implements Runnable {
private WeakReference<Activity> activityRef;
public MyRunnable(Activity activity) {
activityRef = new WeakReference<Activity>(activity);
}
public void run() {
//some code
}
}
private MyRunnable runnable = new MyRunnable(this);
答案 1 :(得分:4)
尝试这样的事情:
private Runnable myRunnable = new Runnable() {
public void run() {
txtStatus.setText("hello");
}
};
// somewhere in code
txtStatus.postDelayed(myRunnable, 1000);
// in onPause or onDestroy
txtStatus.removeCallbacks(myRunnable);
注意:
run
onDestroy
将永远无法调用removeCallbacks
new Handler()
替换为txtStatus
,因为每个View
都有自己的Handler
实例,而无需再创建一个