android – 取消已开始运行的 runnable

huangapple go评论66阅读模式
英文:

android - cancel runnable that already start running

问题

我在后台有一个长时间运行的过程要执行。因此,在 onCreate 中,我会从 handlerThread 发布一个可运行对象到我的处理程序中,但是我有一个按钮允许用户取消它。有可能在 Runnable 开始后停止它吗?

@Override
protected void onCreate(Bundle savedInstanceState) {
    Handler h = new Handler( HandlerThread.getLooper() );
    Runnable runnable = //实现了Runnable接口的类;

    h.post( runnable );

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

但似乎这不会取消已经在运行的可运行对象,那我应该使用带有很大延迟的 postDelayed() 吗?

英文:

I have a long process in the background to do. So onCreate, I post a runnable in my handler from handlerThread but I have a button that allows users to cancel it. It's possible to stop a Runnable after it starts?

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

but it seems that doesn't cancel runnable that already running, Or should I use postDelayed() with a huge delay?

答案1

得分: 0

在你的可运行体内部,有一个名为 running 的布尔标志。

然后,你的按钮可以将这个标志设置为 true 或 false,以便停止它的运行。

你可以实现暂停、恢复,或者开始、停止,这都取决于你的使用情况。

比如:

while(running) {
   // 你重复执行的后台代码
}

或者

if(running) {
   // 执行一些单次代码,例如如果用户在 if 之前按下按钮,则可以在此之前停止它,但在此之后不能停止。
}

你还可以有多个步骤,允许你在中途取消。

if(running) {
  // 执行第一个步骤的代码
}
if(running) {
  // 执行第二个步骤的代码
}
英文:

Inside of your runnable have a boolean flag for running.

Your button then can set this flag to true/false, to stop it running.

You can implement pause, resume, or start, stop, it all depends on your usecase.

i.e. something like

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

or

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. 
}

You could also have multiple steps, allowing you to cancel mid way.

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

答案2

得分: 0

使用以下代码

    handler.removeCallbacksAndMessages(null);
英文:

Use below code

handler.removeCallbacksAndMessages(null);

huangapple
  • 本文由 发表于 2020年8月24日 17:29:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/63558246.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定