Search code examples
javaandroidmemory-leaksandroid-handlerandroid-memory

static runnable in Activity


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


Solution

  • 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