cancelling a handler.postdelayed process

后端 未结 6 1416
粉色の甜心
粉色の甜心 2020-11-28 19:27

I am using handler.postDelayed() to create a waiting period before the next stage of my app takes place. During the wait period I am displaying a dialog with pr

6条回答
  •  春和景丽
    2020-11-28 20:13

    Here is a class providing a cancel method for a delayed action

    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);
    }}
    

提交回复
热议问题