Search code examples
androidhandlerrunnable

How can I stop Handler in postDelayed mode?


How can I stop the counter of the Handler when it shouldn't count anymore? Maybe you can tell me how to do with the code below.

 public void handler() {
    nHandler.postDelayed(new Runnable() {
        @Override
        public void run() {

                viewFlipper.setDisplayedChild(8);
        }
    }, 20000);
}

Solution

  • Use removeCallbacks

    nHandler.removeCallbacks(nhandlerTask);
    

    http://developer.android.com/reference/android/os/Handler.html#removeCallbacks(java.lang.Runnable)

    public final void removeCallbacks (Runnable r)
    
    Added in API level 1
    Remove any pending posts of Runnable r that are in the message queue.