Runnable 运行 只能运行一次
Runnable running only one time
我需要多次执行任务,直到满足特定条件。代码:
handler = new Handler();
runnableCode = new Runnable() {
@Override
public void run() {
doThings();
}
};
handler.postDelayed(runnableCode, 200);
方法 doThings:
private void doThings(){
//conditions are met
stopRunnable();
}
方法停止运行:
private void stopRunnable(){
handler.removeCallbacks(runnableCode);
}
这样,doThings() 方法只执行一次。我应该怎么做?
谢谢
PostDelayed 告诉它在 200 毫秒内调用 unnable。如果您希望它在另一个 200 毫秒内再次被调用,您的可运行对象必须再次 post 自身到处理程序。
我建议你试试:
handler=new Handler();
runnableCode = new Runnable() {
@Override
public void run() {
doThings();
if(condition){
handler.postDelayed(runnableCode, 200);
}
}
};
handler.postDelayed(runnableCode, 200);
方法停止运行:
private void stopRunnable(){
handler.removeCallbacksAndMessages(null);
}
这很简单,递归调用您的 Runnable,如下所示:
handler=new Handler();
runnableCode = new Runnable() {
@Override
public void run() {
doThings();
// just add this line
handler.postDelayed(this, 200);
}
};
handler.postDelayed(runnableCode, 200);
使用 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
这是递归操作,所以你必须添加处理程序。 Postdelayed inside 运行 and outside 请在投反对票前通知,以便我修改答案。
我需要多次执行任务,直到满足特定条件。代码:
handler = new Handler();
runnableCode = new Runnable() {
@Override
public void run() {
doThings();
}
};
handler.postDelayed(runnableCode, 200);
方法 doThings:
private void doThings(){
//conditions are met
stopRunnable();
}
方法停止运行:
private void stopRunnable(){
handler.removeCallbacks(runnableCode);
}
这样,doThings() 方法只执行一次。我应该怎么做?
谢谢
PostDelayed 告诉它在 200 毫秒内调用 unnable。如果您希望它在另一个 200 毫秒内再次被调用,您的可运行对象必须再次 post 自身到处理程序。
我建议你试试:
handler=new Handler();
runnableCode = new Runnable() {
@Override
public void run() {
doThings();
if(condition){
handler.postDelayed(runnableCode, 200);
}
}
};
handler.postDelayed(runnableCode, 200);
方法停止运行:
private void stopRunnable(){
handler.removeCallbacksAndMessages(null);
}
这很简单,递归调用您的 Runnable,如下所示:
handler=new Handler();
runnableCode = new Runnable() {
@Override
public void run() {
doThings();
// just add this line
handler.postDelayed(this, 200);
}
};
handler.postDelayed(runnableCode, 200);
使用 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
这是递归操作,所以你必须添加处理程序。 Postdelayed inside 运行 and outside 请在投反对票前通知,以便我修改答案。