Reputation: 31
calling the method handler.removeMessagesAndCallbacks(null) stops all handlers which are not executed yet (post delayed). but i need a method i can't find which interrupts the handler already running.
a thread can be interrupted while being executed. can a handler also be interrupted like a thread?
here an example:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
> ...
}, 0);
handler.postDelayed(new Runnable() {
> ...
}, 1000);
@Override
protected void onPause() {
> super.onPause();
> handler.removeMessagesAndCallbacks(null);
}
the post delayed handler of 1000 is canceled, but the other handler is still being executed when calling onPause(), when already running.
Can i cancel a handler already being executed? Is there an easier opportunity than Override the Runnable or Handler class? If not, can somebody tell me how to Override, only for the case to cancel the runnable in the handler?
In my case the handlers are executing post delayed animations. I cannot cancel every single animation programatically. the runnable (handler) should be canceled including the animations should be canceled too. Thank you!
Upvotes: 0
Views: 81
Reputation: 1018
I think a good practice for what you want is using kotlin coroutines.
by using coroutines you can define some jobs that can be executed in the main thread or background threads. but the good point about them is that you can cancel them at any time you want by using job.cancel()
.
and if you want to do this with runnable and java maybe this question can help you: Android: How do I stop Runnable?
Upvotes: 0