如果我已经在执行handler.postDelayed
线程,但需要取消它怎么办?
如果我已经在执行handler.postDelayed
线程,但需要取消它怎么办?
根据Android文档,我这样做是为了取消postDelay操作: removeCallbacks方法可以移除消息队列中等待执行的Runnable r。
handler.removeCallbacks(runnableRunner);
或使用它来移除所有消息和回调
handler.removeCallbacksAndMessages(null);
handler.removeCallbacksAndMessages(null);
官方文档指出:
...如果token为空,所有的回调函数和消息将被移除。
我曾经遇到一个情况,需要在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; 以取消句柄,只是为了保持代码清洁,并确保一切都会被清除。