在android eclipse上每秒运行一次的计时器
大家好,你们能帮我创建一个5秒计时器,每3秒或5秒运行一次。。我是android新手,请帮助我 我只创建了一个5秒计时器,但它只运行一次。。我希望它每5秒运行一次 这是我的代码:在android eclipse上每秒运行一次的计时器,android,eclipse,Android,Eclipse,大家好,你们能帮我创建一个5秒计时器,每3秒或5秒运行一次。。我是android新手,请帮助我 我只创建了一个5秒计时器,但它只运行一次。。我希望它每5秒运行一次 这是我的代码: txt1 = (TextView)findViewById(R.id.textView1); final Handler handler = new Handler(); TimerTask task = new TimerTask() { @Override pu
txt1 = (TextView)findViewById(R.id.textView1);
final Handler handler = new Handler();
TimerTask task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
// pos=rand.nextInt(10);
//txt1.setText(""+pos);
if(Integer.parseInt(txt1.getText().toString()) != 0)
{
txt1.setText("" + (Integer.parseInt(txt1.getText().toString()) - 1));
}
}
});
}
};
Timer timer = new Timer();
timer.schedule(task, 1000, 1000);
Thx:您可以使用下面的代码来完成,处理程序会一次又一次地调用自身
final Handler handler = new Handler();
Runnable runable = new Runnable() {
@Override
public void run() {
try{
if(Integer.parseInt(txt1.getText().toString()) != 0)
{
txt1.setText("" + (Integer.parseInt(txt1.getText().toString()) - 1));
}
handler.postDelayed(this, 3000);
}
catch (Exception e) {
// handle exception
}
}
};
handler.postDelayed(runable, 5000);
这里有一个类似的问题:。你用过实际的计时器吗?你知道你需要重置它们,以便它们再次触发。我的应用程序崩溃了,先生,它的内存不足,还有其他方法吗?犯了一个错误,最后不需要了。基本思想是多次调用它,就像递归一样。当我将代码添加到你的代码中时,计时器没有重新启动,它只是在0处被阻塞。看看我做了什么,sirwell它仍然停留在0,没有重新启动,但幸好它现在没有崩溃,