java - 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!
解决方案
我认为你想要的一个好习惯是使用 kotlin 协程。通过使用协程,您可以定义一些可以在主线程或后台线程中执行的作业。但它们的好处是您可以随时使用 取消它们job.cancel()
。
如果你想用 runnable 和 java 做到这一点,也许这个问题可以帮助你: Android:我如何停止 Runnable?
推荐阅读
- python - 使用 ElementTree 从文件夹中读取多个 xml 文件
- javascript - 在没有json的两个数组中查找匹配值
- angular - 角材料选项卡初始活动选项卡
- symfony - 无法在 Symfony 3.4 和 FosUserBundle 中自动装配服务
- python - 如何使用 python 类型指定这种可变参数元组?
- r - 在 Azure Databricks 上安装 rgdal 和 rgeos
- python - 如何在 python 中纯粹使用 ipd.audio 编写 wav 文件?
- javascript - {handleButton}: {handleButton:()=>void} 在示例中是什么意思
- c# - 如何为 Azure 函数使用自定义计时器?
- javascript - 音频元素不播放