Android 取消可运行
我终于把另一篇文章整理好了;创建一种每秒左右更新GUI的方法。因此,我的runnable运行良好,但现在我在GUI中添加了一个按钮,用于停止runnable。但是你怎么做呢 我尝试过以下代码:Android 取消可运行,android,Android,我终于把另一篇文章整理好了;创建一种每秒左右更新GUI的方法。因此,我的runnable运行良好,但现在我在GUI中添加了一个按钮,用于停止runnable。但是你怎么做呢 我尝试过以下代码: // Button to stop the runnable stop = ( Button ) findViewById( R.id.stop ); stop.setOnClickListener( new View.OnClickListener() { @
// Button to stop the runnable
stop = ( Button ) findViewById( R.id.stop );
stop.setOnClickListener( new View.OnClickListener()
{
@Override
public void onClick(View v)
{
handler.removeCallbacksAndMessages( timerTask.class );
}
});
我实现Runnable是为了使用它,因此我不会手动创建一个新线程并向其中添加run()方法。那你怎么做呢
谢谢你不能把线弄坏。您需要做的是在
Runnable
对象实现中添加一个方法来确认停止请求。然后,该方法翻转一个条件,使Runnable.run()
方法退出
public class YourClass implements Runnable {
private boolean keepGoing = true;
public void run() {
while(keepGoing) {
// Do important work!
}
}
public void stop() {
this.keepGoing = false;
}
}
因此,在您的停止按钮的
onClick(View v)
实现中,您可以调用yourClassInstance.stop()
。这就打破了循环,run()
方法结束,线程被清理干净。你能详细说明一下吗?我尝试了你上面所说的,代码才刚刚开始-GUI没有改变*对不起,我的意思是根本没有启动。GUI不会更新,但run()和while()方法都是entered@Katana24编辑了我的答案,希望有帮助。