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 after ondestroy if call removecallbacks
  • i replaced new handler() txtstatus, because every view has own instance of handler , there no need create additional one

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -