首页 > 解决方案 > after onPause() method stop "active" handler

问题描述

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!

标签: javaandroidhandleronpause

解决方案


我认为你想要的一个好习惯是使用 kotlin 协程。通过使用协程,您可以定义一些可以在主线程或后台线程中执行的作业。但它们的好处是您可以随时使用 取消它们job.cancel()

如果你想用 runnable 和 java 做到这一点,也许这个问题可以帮助你: Android:我如何停止 Runnable?


推荐阅读