android - 取消已经启动的可运行对象 运行

android - cancel runnable that already start running

我在后台有一个很长的过程要做。所以 onCreate,我 post 我的处理程序中的可运行程序来自 handlerThread,但我有一个允许用户取消它的按钮。 Runnable 启动后可以停止吗?

@Override
protected void onCreate(Bundle savedInstanceState) {
    Handler h = new Handler( HandlerThread.getLooper() );
    Runnable runnable = //class that implements runnable;

    h.post( runnable );

    btn.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            h.removeCallbacks(runnable);
        }
    }
}

但似乎并没有取消已经 运行 的可运行,或者我应该使用 postDelayed() 并延迟很长时间吗?

在你的 runnable 里面有一个 running 的布尔标志。

然后您的按钮可以将此标志设置为 true/false,以停止它 运行。

您可以实现暂停、恢复或启动、停止,这完全取决于您的用例。

即像

while(running) {
   // Your repeated background code
}

if(running) {
   // do some one shot code, i.e. the user can stop it if they press the button before the if, but not after. 
}

您也可以有多个步骤,允许您中途取消。

if(running) {
  // do step 1 code
}
if(running) {
  // do step 2 code
}

使用下面的代码

handler.removeCallbacksAndMessages(null);