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.
removecallback and handler = null; to cancel out the handle just to keep the code clean and make sure everything will be removed.
Just use the removeCallbacks(Runnable r) method.
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With