Reputation: 5975
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)?
Upvotes: 2
Views: 5056
Reputation: 2303
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);
Upvotes: 5
Reputation: 22232
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:
run
will never be called after onDestroy
if you call removeCallbacks
new Handler()
with txtStatus
, because every View
has its own instance of Handler
and there is no need to create additional oneUpvotes: 5