我使用handler.postDelayed()在我的应用程序的下一阶段发生之前创建一个等待期。在等待期间,我将显示一个对话框的进度条和取消按钮。

我的问题是我无法找到一种方法来取消postDelayed任务之前的时间流逝。


当前回答

下面是一个为延迟操作提供取消方法的类

public class DelayedAction {

private Handler _handler;
private Runnable _runnable;

/**
 * Constructor
 * @param runnable The runnable
 * @param delay The delay (in milli sec) to wait before running the runnable
 */
public DelayedAction(Runnable runnable, long delay) {
    _handler = new Handler(Looper.getMainLooper());
    _runnable = runnable;
    _handler.postDelayed(_runnable, delay);
}

/**
 * Cancel a runnable
 */
public void cancel() {
    if ( _handler == null || _runnable == null ) {
        return;
    }
    _handler.removeCallbacks(_runnable);
}}

其他回答

下面是一个为延迟操作提供取消方法的类

public class DelayedAction {

private Handler _handler;
private Runnable _runnable;

/**
 * Constructor
 * @param runnable The runnable
 * @param delay The delay (in milli sec) to wait before running the runnable
 */
public DelayedAction(Runnable runnable, long delay) {
    _handler = new Handler(Looper.getMainLooper());
    _runnable = runnable;
    _handler.postDelayed(_runnable, delay);
}

/**
 * Cancel a runnable
 */
public void cancel() {
    if ( _handler == null || _runnable == null ) {
        return;
    }
    _handler.removeCallbacks(_runnable);
}}

如果您确实有多个内部/匿名可运行程序传递给同一个处理程序,并且您希望在同一事件使用时取消所有可运行程序

handler.removeCallbacksAndMessages(空);

根据文件, 删除所有obj为的回调和已发送消息的挂起post 令牌。如果token为空,所有回调和消息将被删除。

它为我工作,当我调用CancelCallBacks(this)在post delayed runnable通过一个布尔值传递它

Runnable runnable = new Runnable(){
    @Override
    public void run() {
        Log.e("HANDLER", "run: Outside Runnable");
        if (IsRecording) {
            Log.e("HANDLER", "run: Runnable");
            handler.postDelayed(this, 2000);
        }else{
            handler.removeCallbacks(this);
        }
    }
};

另一种方法是处理Runnable本身:

Runnable r = new Runnable {
    public void run() {
        if (booleanCancelMember != false) {
            //do what you need
        }
    }
}

我这样做是为了发布一个延迟的可运行文件:

myHandler.postDelayed(myRunnable, SPLASH_DISPLAY_LENGTH); 

删除它:myhandler。removecallbacks (myRunnable);