cancelling a handler.postdelayed process

后端 未结 6 1403
粉色の甜心
粉色の甜心 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:07

    Hope this gist help https://gist.github.com/imammubin/a587192982ff8db221da14d094df6fb4

    MainActivity as Screen Launcher with handler & runnable function, the Runnable run to login page or feed page with base preference login user with firebase.

    0 讨论(0)
  • 2020-11-28 20:08

    Another way is to handle the Runnable itself:

    Runnable r = new Runnable {
        public void run() {
            if (booleanCancelMember != false) {
                //do what you need
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-28 20:10

    In case you do have multiple inner/anonymous runnables passed to same handler, and you want to cancel all at same event use

    handler.removeCallbacksAndMessages(null);

    As per documentation,

    Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

    0 讨论(0)
  • 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);
    }}
    
    0 讨论(0)
  • 2020-11-28 20:14

    It worked for me when I called CancelCallBacks(this) inside the post delayed runnable by handing it via a boolean

    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);
            }
        }
    };
    
    0 讨论(0)
  • 2020-11-28 20:15

    I do this to post a delayed runnable:

    myHandler.postDelayed(myRunnable, SPLASH_DISPLAY_LENGTH); 
    

    And this to remove it: myHandler.removeCallbacks(myRunnable);

    0 讨论(0)
提交回复
热议问题