Casa > H > How To Stop A Running Handler In Android

How to stop a running handler in Android

main-qimg-78dfe9874c0a4e246f5ddded3fc0abc9-mzj

You can use:

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

Or you can use:

  1. 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:

  1. Handler handler= new Handler() 
  2. Runnable myRunnable = new Runnable() { 
  3. public void run() { 
  4. // do something 
  5. }; 
  6. handler.postDelayed(myRunnable,zeit_dauer2); 

Then:

  1. 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:

  1. @Override 
  2. public void onClick(View v) { 
  3. Crunch(); 
  4. Handler handler= new Handler(); 
  5. Runnable myRunnable = new Runnable() { 

To:

  1. @Override 
  2. public void onClick(View v) { 
  3. Crunch(); 
  4. handler= new Handler(); 
  5. 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.

  1. Handler handler; // declared before onCreate 
  2. Runnable myRunnable; 

De Leesen Nadolski

Como digitar Hindi no PowerPoint :: O meu Moto E reinicia-se automaticamente. O que posso fazer?