ben75
ben75

Reputation: 28706

Handler.postAtTime vs Handler.postDelayed

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?

Upvotes: 6

Views: 7149

Answers (4)

algrid
algrid

Reputation: 5954

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.

Upvotes: 1

njzk2
njzk2

Reputation: 39406

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

Upvotes: 2

wtsang02
wtsang02

Reputation: 18863

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    }

Upvotes: 5

psykhi
psykhi

Reputation: 2981

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

Upvotes: 0

Related Questions