Handler.postAtTime vs Handler.postDelayed

The android Handler class contains this method:

public final boolean postAtTime (Runnable r, Object token, long uptimeMillis) 

to publish runnable at a given time. token can be used later to remove the r callback from the message queue thanks to this method:

 public final void removeCallbacks (Runnable r, Object token) 

The following class does not exist in the Handler class

 public final boolean postDelayed (Runnable r, Object token, long delay) 

Is there any good reason not to provide such a method?

+6
source share
3 answers

After viewing the source code, the marker object finally proceeds 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 you need

 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 he is the same.

Refresh, 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 } 
+5
source

Looking at the source of Handler, it seems that there are:

 private final Message getPostMessage(Runnable r, Object token) { Message m = Message.obtain(); m.obj = token; m.callback = r; return m; } 

Who 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 use removeCallbacks() with token as param

+2
source

To remove postDelayed runnable r from H handler, simply call H.removeCallbacks (r). Why do we need a token?

0
source

All Articles