How to stop a running handler in Android
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:
- @Override
- public void onClick(View v) {
- Crunch();
- Handler handler= new Handler();
- Runnable myRunnable = new Runnable() {
To:
- @Override
- public void onClick(View v) {
- Crunch();
- 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 onCreate
- Runnable myRunnable;