Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel a handler before time in Android code?

Tags:

I create 1 minute delayed timer to shutdown service if it's not completed. Looks like this:

private Handler timeoutHandler = new Handler(); 

inside onCreate()

timeoutHandler.postDelayed(new Runnable()         {             public void run()             {                 Log.d(LOG_TAG, "timeoutHandler:run");                  DBLog.InsertMessage(getApplicationContext(), "Unable to get fix in 1 minute");                 finalizeService();             }         }, 60 * 1000); 

If I get job accomplished before this 1 minute - I would like to get this delayed thing cancelled but not sure how.

like image 944
katit Avatar asked May 04 '11 15:05

katit


People also ask

How do I cancel handler?

removecallback and handler = null; to cancel out the handle just to keep the code clean and make sure everything will be removed.

How do I remove runnable from Handler?

Just use the removeCallbacks(Runnable r) method.

How do you close handler thread?

postDelayed(new Runnable() { @Override public void run() { Intent i = new Intent(MapsActivity. this,MapsActivity. class); startActivity(i); finish(); } }, TIME_OUT); Then you can use Handler#removeCallbacksAndMessages to remove this or any callback.

What is Handler postDelayed in Android?

postDelayed(Runnable r, Object token, long delayMillis) Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. final void. removeCallbacks(Runnable r) Remove any pending posts of Runnable r that are in the message queue.


2 Answers

You can't really do it with an anonymous Runnable. How about saving the Runnable to a named variable?

Runnable finalizer = new Runnable()     {         public void run()         {             Log.d(LOG_TAG, "timeoutHandler:run");              DBLog.InsertMessage(getApplicationContext(), "Unable to get fix in 1 minute");             finalizeService();         }     }; timeoutHandler.postDelayed(finalizer, 60 * 1000);  ...  // Cancel the runnable timeoutHandler.removeCallbacks(finalizer); 
like image 51
Brian Dupuis Avatar answered Oct 16 '22 02:10

Brian Dupuis


If you don't want to keep a reference of the runnable, you could simply call:

timeoutHandler.removeCallbacksAndMessages(null); 

The official documentation says:

... If token is null, all callbacks and messages will be removed.

like image 45
AbdelHady Avatar answered Oct 16 '22 02:10

AbdelHady