java - static runnable in Activity -
i modifying following code in 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 doesn't work, since we're referencing 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 initial example rewritten use static class instead of anonymous inner class (to avoid potential of memory leak)?
try 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,
run
never called afterondestroy
if callremovecallbacks
- i replaced
new handler()
txtstatus
, because everyview
has own instance ofhandler
, there no need create additional one
Comments
Post a Comment