Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handler.postAtTime vs Handler.postDelayed

Tags:

java

android

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 ?

like image 491
ben75 Avatar asked Feb 04 '13 15:02

ben75


3 Answers

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    }
like image 147
wtsang02 Avatar answered Oct 05 '22 21:10

wtsang02


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

like image 22
njzk2 Avatar answered Oct 05 '22 20:10

njzk2


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.

like image 31
algrid Avatar answered Oct 05 '22 20:10

algrid