Stop handler.postDelayed() Stop handler.postDelayed() android android

Stop handler.postDelayed()


You can use:

 Handler handler = new Handler() handler.postDelayed(new Runnable())

Or you can use:

 handler.removeCallbacksAndMessages(null);

Docs

public final void removeCallbacksAndMessages (Object token)

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

Or you could also do like the following:

Handler handler =  new Handler()Runnable myRunnable = new Runnable() {public void run() {    // do something}};handler.postDelayed(myRunnable,zeit_dauer2);

Then:

handler.removeCallbacks(myRunnable);

Docs

public final void removeCallbacks (Runnable r)

Added in API level 1 Remove any pending posts of Runnable r that are in the message queue.

public final void removeCallbacks (Runnable r, Object token)

Edit:

Change this:

@Overridepublic void onClick(View v) {    Handler handler =  new Handler();    Runnable myRunnable = new Runnable() {

To:

@Overridepublic void onClick(View v) {    handler = new Handler();    myRunnable = new Runnable() { /* ... */}

Because you have the below. Declared before onCreate but you re-declared and then initialized it in onClick leading to a NPE.

Handler handler; // declared before onCreateRunnable myRunnable;


You can define a boolean and change it to false when you want to stop handler. Like this..

boolean stop = false;handler.postDelayed(new Runnable() {    @Override    public void run() {        //do your work here..        if (!stop) {            handler.postDelayed(this, delay);        }    }}, delay);


this may be old, but for those looking for answer you can use this...

public void stopHandler() {   handler.removeMessages(0);}

cheers