I am modifying the following code in my activity:

new Handler().postDelayed(new Runnable() {
 public void run() {
    txtStatus.setText("hello");
  }
}, 1000);

to:

static Runnable myRunnable = new Runnable() {
public void run() {
   txtStatus.setText("hello");
};

new Handler().postDelayed(myRunnable, 1000);

Which obviously doesn't work, since we're referencing a non static variable.

This doesn't work either:

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);

so how would my initial example be rewritten to use a static class instead of an anonymous inner class (to avoid the potential of a memory leak)?

有帮助吗?

解决方案 2

Try something like this:

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);

Notes:

  • this avoids memory leaks, as your run will never be called after onDestroy if you call removeCallbacks
  • I replaced new Handler() with txtStatus, because every View has its own instance of Handler and there is no need to create additional one

其他提示

You can use WeakReference to avoid memory leak problems. Here is some code, which illustrate this idea

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top