如果我有 handler.postDelayed线程已经在执行,我需要取消它?
handler.postDelayed
我这样做是为了取消 postDelays,根据 Android: removeCallbacks删除消息队列中 Runnable r 的所有挂起的帖子。
handler.removeCallbacks(runnableRunner);
or use to remove all messages and callbacks
handler.removeCallbacksAndMessages(null);
If you don't want to keep a reference of the runnable, you could simply call:
官方文件说:
... 如果标记为空,则将删除所有回调和消息。
我有一个实例,需要在它运行的过程中取消 postDelayed,因此上面的代码对我的示例不起作用。最后我在 Runnable 内部做了一个布尔检查,这样当代码在给定的时间后执行时,它要么根据当时的布尔值触发,这对我来说是有效的。
public static Runnable getCountRunnable() { if (countRunnable == null) { countRunnable = new Runnable() { @Override public void run() { if (hasCountStopped) getToast("The count has stopped"); } }; } return countRunnable; }
仅供参考——在我的活动破坏中,我确实使用了其他开发人员建议的代码: handler.Removecallback 和 handler = null; 来取消句柄,只是为了保持代码的整洁,并确保所有内容都被删除。