[英]android - cancel runnable that already start running
我在后台有一个很长的过程要做。 所以onCreate
,我从handlerThread
在我的处理程序中发布了一个 runnable ,但我有一个按钮,允许用户取消它。 启动后可以停止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);
}
}
}
但似乎并没有取消已经在运行的 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.