这是一个我希望每3秒后重复50次的代码。如果我用'for'循环或'while'循环调用此函数它不能正常工作请给我建议。
for (int i = 0; i < 50; i++) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Generate_Ballon();
}
}, delay);
}
答案 0 :(得分:1)
您可以使用CountDownTimer
参见示例,
new CountDownTimer(150000, 3000)
{
public void onTick(long millisUntilFinished)
{
// You can do your for loop work here
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
此处onTick()
方法将每3秒执行一次。
答案 1 :(得分:0)
为此,您应该使用Handler的postDelayed函数。它将在主UI线程上以指定的延迟运行您的代码,因此您将能够更新UI控件。
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
@Override
protected void onCreate(Bundle bundle) {
...
mHandler = new Handler();
}
Runnable mStatusChecker = new Runnable() {
@Override
public void run() {
updateStatus(); //this function can change value of mInterval.
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
答案 2 :(得分:0)
试试这个
private static int i = 0;
void runHandler()
{
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
i++;
if(i<50)
runHandler();
Generate_Ballon();
}
}, delay);
}
答案 3 :(得分:0)
private int count = 50;
private Handler handler = new Handler();
private Runnable r = new Runnable() {
public void run() {
Generate_Ballon();
if (--count > 0) {
handler.postDelayed(r, delay);
}
}
};
handler.postDelayed(r, delay);