The android Handler class contains this method :
public final boolean postAtTime (Runnable r, Object token, long uptimeMillis)
to post a Runnable at a given time. The token
can be used later to remove the callback to r
from the message queue thanks to this method:
public final void removeCallbacks (Runnable r, Object token)
The following method doesn't exist in the Handler class
public final boolean postDelayed (Runnable r, Object token, long delay)
Is there a good reason for not providing such a method ?
After looking at the source code, the token object eventually passes to the Message:
public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
308 {
309 return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
310 }
private static Message getPostMessage(Runnable r, Object token) {
608 Message m = Message.obtain();
609 m.obj = token;
And postDelay
public final boolean postDelayed(Runnable r, long delayMillis)
330 {
331 return sendMessageDelayed(getPostMessage(r), delayMillis);
332 }
If what you want is
public final boolean postDelayed (Runnable r, Object token, long delay)
Then why not just use
public final boolean postAtTime (Runnable r, Object token, long uptimeMillis)
since its the same.
Update, forgot to add this:
public final boolean sendMessageDelayed(Message msg, long delayMillis)
442 {
443 if (delayMillis < 0) {
444 delayMillis = 0;
445 }
446 return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
447 }
Looking at Handler source, it appears that there is :
private final Message getPostMessage(Runnable r, Object token) {
Message m = Message.obtain();
m.obj = token;
m.callback = r;
return m;
}
Which can be copied for what you want : Instead of calling postDelayed
, wrap your runnable in such a message
sendMessageDelayed(getPostMessage(r, token), delayMillis);
you can then use removeCallbacks()
with token as param
This is an old question, but the postDelayed
method version taking a token as an argument was added in API 28: see https://developer.android.com/reference/android/os/Handler#postDelayed(java.lang.Runnable,%20java.lang.Object,%20long)
For older API versions one still has to use postAtTime
if a token is required to remove the callback later.
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