My Problem is that I need to send messages with a delay of 1 second. The handler then initiates some action, you're getting the picture.
There are nevertheless some conditions in which the already sent message should be deleted ( before the second elapsed ) to prevent the handler from doing anything. I couldn't figure out how to do this ( or if it's even possible ), so If anyone of you has a clue, please let me know..
Many developers and much of the source code you'll find will show people passing anonymous functions to a handler, so I think in some cases you may be unsure how to remove these. A simple solution is to declare your runnable as you would any other object, and keep a pointer to it which can be used to clear any instance of it from the Handler queue.
private Runnable lastMyRunnablePtr = null;
...
private class MyRunnable implements Runnable
{}
....
lastMyRunnablePtr = new MyRunnable();
mHandler.postDelayed(lastMyRunnablePtr ,30000);
....
protected void onDestroy() {
mHandler.removeCallbacks(lastMyRunnablePtr);
}
There is nothing scary about the removeMessages()
methods; they are perfectly safe. The framework relies heavily on these methods and they are used in many many places, especially in the default widgets (View
, ListView
, etc.) It's much much better than building a Handler
that ignores specific messages. This is programming, don't go with your feelings :p
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With