我需要多次执行任务,直到满足某些条件。代码:
handler = new Handler();
runnableCode = new Runnable() {
@Override
public void run() {
doThings();
}
};
handler.postDelayed(runnableCode, 200);
方法doThings:
private void doThings(){
//conditions are met
stopRunnable();
}
方法stopRunnable:
private void stopRunnable(){
handler.removeCallbacks(runnableCode);
}
这样,doThings()方法只执行一次。我该怎么办?
由于
答案 0 :(得分:2)
我建议你试试:
handler=new Handler();
runnableCode = new Runnable() {
@Override
public void run() {
doThings();
if(condition){
handler.postDelayed(runnableCode, 200);
}
}
};
handler.postDelayed(runnableCode, 200);
方法stopRunnable:
private void stopRunnable(){
handler.removeCallbacksAndMessages(null);
}
答案 1 :(得分:0)
PostDelayed告诉它在200ms内调用unnable。如果你希望在另一个200ms内再次调用它,你的runnable必须再次将它自己发送给Handler。
答案 2 :(得分:0)
这很简单,递归调用你的Runnable,如下所示:
handler=new Handler();
runnableCode = new Runnable() {
@Override
public void run() {
doThings();
// just add this line
handler.postDelayed(this, 200);
}
};
handler.postDelayed(runnableCode, 200);
答案 3 :(得分:0)
使用Kotlin
fun handler() {
handler = Handler()
var count: Int = 0
runnabl = Runnable {
kotlin.run {
count++
Toast.makeText(this,"$count",10000).show()
// Route.mToast(this, "hello +$count")
//must add this
handler.postDelayed(runnabl, 10000) //--------repeat each interval
}
}
count++
//must add this
handler.postDelayed(runnabl, 2000) //----------------starthere------
};
lateinit var runnabl: Runnable
lateinit var handler: Handler
这是重新启动操作,因此您必须添加处理程序。在内部运行和外部运行中延迟后,请在下降投票之前通知,以便我修改答案。