如何在Android代码中提前取消处理程序? [英] How to cancel a handler before time in Android code?
本文介绍了如何在Android代码中提前取消处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个延迟1分钟的计时器来关闭服务(如果尚未完成).看起来像这样:
I create 1 minute delayed timer to shutdown service if it's not completed. Looks like this:
private Handler timeoutHandler = new Handler();
在onCreate()里面
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);
如果我在这1分钟之前完成工作-我想取消这个延迟的事情,但不确定如何做.
If I get job accomplished before this 1 minute - I would like to get this delayed thing cancelled but not sure how.
推荐答案
使用匿名Runnable不能真正做到这一点.如何将Runnable保存到命名变量?
You can't really do it with an anonymous Runnable. How about saving the Runnable to a named variable?
Runnable finalizer = new Runnable()
{
public void run()
{
Log.d(LOG_TAG, "timeoutHandler:run");
DBLog.InsertMessage(getApplicationContext(), "Unable to get fix in 1 minute");
finalizeService();
}
};
timeoutHandler.postDelayed(finalizer, 60 * 1000);
...
// Cancel the runnable
timeoutHandler.removeCallbacks(finalizer);
这篇关于如何在Android代码中提前取消处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文