我正在寻找一种在按下按钮后每30秒增加一个整数的方法。我遇到的问题是我的代码当前等待30秒将整数增加1,但之后每个整数只增加一秒。这是我的代码。
int delay = 5000; // delay for 5 sec.
int period = 30000; // repeat every 30 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if(ammo_remaining<10){
update_ammo();``
}
}
});
}
}, delay, period);
答案 0 :(得分:0)
尝试使用处理程序:
int delay = 5000; // delay for 5 sec.
int period = 30000; // repeat every 30 sec.
Handler handler=new Handler();
protected void your_calling_method()
{
handler.postDelayed(r, delay);
}
Runnable r=new Runnable()
{
public void run()
{
if(ammo_remaining<10)
{
update_ammo();
}
handler.postDelayed(r, period);
};
};
答案 1 :(得分:0)
Button btn = (Button)findViewById(R.id.your button);
// first get your button;
final Handler hand = new Handler();
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
hand.post(new Runnable(){
@override public void run(){
(your int)++; // this will increase your int on step;
hand.postDelayed(this,30*1000); // this will do the same thing after 30 seconds again;
}
}
}
});
答案 2 :(得分:0)
将递归后延迟调用移动到您的(ammo&lt; 10)if语句中可以为您提供所需的行为。
int delay = 5000; // delay for 5 sec.
int period = 30000; // repeat every 30 sec.
int ammo_remaining = 10;
boolean reloading = false;
Handler handler=new Handler();
protected void shoot()
{
ammo_remaining--;
update_ammo();
if( ! reloading) //if not reloading
{
reloading = true;
handler.postDelayed(r, delay);
}
}
Runnable r=new Runnable()
{
public void run()
{
if(ammo_remaining<10)
{
ammo_remaining++;
update_ammo();
handler.postDelayed(r, period);
}
else{reloading=false;}
};
};
编辑:
多次拍摄时,你通过处理程序创建了许多runnable实例,所有这些都在前30秒后泛滥......你只需要创建一个布尔标志来跟踪第一个重新加载的请求< / p>
重新加载&#39;标志和检查应该做的伎俩...