如何在 Android 代码中提前取消处理程序?
我创建了 1 分钟延迟计时器来关闭服务(如果服务未完成)。看起来像这样:
private Handler timeoutHandler = new Handler();
在 onCreate() 内部
timeoutHandler.postDelayed(new Runnable()
{
public void run()
{
Log.d(LOG_TAG, "timeoutHandler:run");
DBLog.InsertMessage(getApplicationContext(), "Unable to get fix in 1 minute");
finalizeService();
}
}, 60 * 1000);
如果我在这 1 分钟之前完成工作 - 我想取消这个延迟的事情,但不知道如何取消。
I create 1 minute delayed timer to shutdown service if it's not completed. Looks like this:
private Handler timeoutHandler = new Handler();
inside onCreate()
timeoutHandler.postDelayed(new Runnable()
{
public void run()
{
Log.d(LOG_TAG, "timeoutHandler:run");
DBLog.InsertMessage(getApplicationContext(), "Unable to get fix in 1 minute");
finalizeService();
}
}, 60 * 1000);
If I get job accomplished before this 1 minute - I would like to get this delayed thing cancelled but not sure how.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您实际上无法使用匿名 Runnable 来做到这一点。将 Runnable 保存到命名变量怎么样?
You can't really do it with an anonymous Runnable. How about saving the Runnable to a named variable?
如果您不想保留可运行的引用,您可以简单地调用:
官方文档说:
If you don't want to keep a reference of the runnable, you could simply call:
The official documentation says:
您可能希望将
postDelayed
的使用替换为sendMessageDelayed
的使用,如下所示:然后发布消息:
然后取消:
无需跟踪可运行程序。
You might want to replace use of
postDelayed
with use ofsendMessageDelayed
like so:Then post a Message:
and then cancel:
No tracking of the runnable necessary.
使用
Handler.removeCallbacks(yourRunnable )
。Use
Handler.removeCallbacks(yourRunnable)
.