Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete delayed messages before they arrive at a Handler?

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..

like image 253
moritz Avatar asked Dec 28 '09 16:12

moritz


2 Answers

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);
}
like image 65
Adrian Lopez Avatar answered Nov 15 '22 17:11

Adrian Lopez


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

like image 36
Romain Guy Avatar answered Nov 15 '22 18:11

Romain Guy