如何取消处理程序在code?程序、code

2023-09-06 13:29:04 作者:缭繞

我创造100分钟延时定时器关机服务,如果它没有完成。看起来是这样的:

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);