removeCallbacksAndMessages

removeCallbacksAndMessages

我的问题是:我使用Handler.postDelayed()在500毫秒后运行动画。稍后在代码中,我使用Handler.removeCallbacksAndMessages(),因为有时我想运行另一个动画。问题是,有时第一个动画已开始但尚未完成,我认为这是同步问题。

有没有一种方法可以检查是否启动了给postDelayed()的Runnable,并且在这种情况下取​​消了removeCallbacksAndMessages()?

如果从此Runnable启动run(),removeCallbacksAndMessages是否有效果?

代码是这样的:

Handler hand = new Handler();
if (counter==2) {
    one = (ImageView) findViewById(img_id);
    two = im;
    hand.postDelayed(new Runnable() {
        public void run() {
    applyAnim(0, 90, one, false);
    applyAnim(0, 90, two, false);
    counter = 0;
        }
    }, 750);
} else (counter == 3) {
    im.setClickable(false);
    hand.removeCallbacksAndMessages(null);
    counter = 1;
    applyScndAnim(0, 90, one, false);
    applyScndAnim(0, 90, two, false);
}

最佳答案

每次您发布一些任务或发送一些消息时,该对象都会添加到队列中。当您调用removeCallbacksAndMessages时,此队列被清除。但是,当您调用removeCallbacksAndMessages时正在分派(已从队列中拉出)的任务或消息不会被取消。如果要停止任务,请作为线程执行:

public class DrawableTask implements Runnable{
    private boolean cancel = false;
    private boolean isBeingDispatched = false;
    public void cancel(){
        if (this.isBeingDispatched())
            this.cancel = true;
    }
    public boolean isBeingDispatched(){ return isBeingDispatched;}
    public void run(){
        isBeingDispatched = true;
        while(!cancel){
            //refresh
        }
        cancel = false;
        isBeingDispatched = false;
    }
}


编辑:

private boolean cancel = false;
private boolean isBeingDispatched = false;

public void cancel(){
    if (this.isBeingDispatched())
        this.cancel = true;
}
public boolean isBeingDispatched(){ return isBeingDispatched;}

public void setHandlers(){
    Handler handler = new Handler(){
        public void handleMessage(Message msg){
             YourClassName.this.cancel = false;
             YourClassName.this.isBeingDispatched = true;
             while(! YourClassName.this.cancel){

                  //refresh
             }
             YourClassName.this.cancel = false;
             YourClassName.this.isBeingDispatched = false;
        }
    };
}


因此,您可以将此取消选项添加到处理程序中。消息到达时,处理程序将执行此代码,如果在执行过程中您调用cancel()方法,则处理程序将暂停他正在执行的所有操作。

关于android - android postDelayed和removeCallbacksAndMessages同步,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11205167/

10-10 08:11