How to remove a runnable from a handler object added by postDelayed?

I have an "open" animation and am using Handler.postDelayed(Runnable, delay) to trigger a "close" animation after a short delay. However, during the time between open and close, there is possibly another animation triggered by a click.

My question is, how would I cancel the "close" animation in the handler?

56763 次浏览

如果你使用递归,你可以通过传递“ this”来实现。

public void countDown(final int c){
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
aq.id(R.id.timer).text((c-1)+"");
if(c <= 1){
aq.id(R.id.timer).gone();
mHandler.removeCallbacks(this);
}else{
countDown(c-1);
}
}
}, 1000);
}

此示例将每秒设置一个 TextView (计时器)的文本,并进行倒计时。一旦它达到0,它将从 UI 中移除 TextView 并禁用倒计时。这只对使用递归的人有用,但是我来这里是为了寻找它,所以我发布了我的结果。

Cristian 的答案是正确的,但是与答案的注释相反,您实际上可以通过调用 removeCallbacksAndMessages(null);来删除匿名 Runnables的回调

给你所述:

删除任何回调挂起的帖子,并发送 obj 为令牌的消息。

This is a late answer, but here's a different method for when you only want to remove a specific category of runnables from the handler (i.e. in OP's case, just remove the close animation, leaving other runnables in the queue):

    int firstToken = 5;
int secondToken = 6;


//r1 to r4 are all different instances or implementations of Runnable.
mHandler.postAtTime(r1, firstToken, 0);
mHandler.postAtTime(r2, firstToken, 0);
mHandler.postAtTime(r3, secondToken, 0);


mHandler.removeCallbacksAndMessages(firstToken);


mHandler.postAtTime(r4, firstToken, 0);

The above code will execute "r3" and then "r4" only. This lets you remove a specific category of runnables defined by your token, without needing to hold any references to the runnables themselves.

注意: 源代码只使用“ = =”操作数比较标记(它不调用。Equals ()) ,因此最好使用 int/Integers 而不是字符串作为标记。