Please note that one should define a Handler
and a Runnable
in class scope, so that it is created once.removeCallbacks(Runnable)
works correctly unless one defines them multiple times. Please look at following examples for better understanding:
Incorrect way :
public class FooActivity extends Activity {
private void handleSomething(){
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
doIt();
}
};
if(shouldIDoIt){
//doIt() works after 3 seconds.
handler.postDelayed(runnable, 3000);
} else {
handler.removeCallbacks(runnable);
}
}
public void onClick(View v){
handleSomething();
}
}
If you call onClick(..)
method, you never stop doIt()
method calling before it call. Because each time creates new Handler
and new Runnable
instances. In this way, you lost necessary references which belong to handler and runnable instances.
Correct way :
public class FooActivity extends Activity {
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
doIt();
}
};
private void handleSomething(){
if(shouldIDoIt){
//doIt() works after 3 seconds.
handler.postDelayed(runnable, 3000);
} else {
handler.removeCallbacks(runnable);
}
}
public void onClick(View v){
handleSomething();
}
}
In this way, you don't lost actual references and removeCallbacks(runnable)
works successfully.
Key sentence is that 'define them as global in your Activity
or Fragment
what you use'.