我需要在健康状况下每秒使健康状况下降“1”,或者等于20以显示“alertDialog”我在代码中没有任何错误。在“健康”通过边界/限制应用程序粉碎后,问题是粉碎,我不知道为什么会发生这种情况,是否有人帮助我? 我还确保有一次使用布尔值显示“alertDialog”,但没有帮助...... 谢谢你的建议:)
代码:
new Timer().schedule(new TimerTask() {
@Override
public void run() {
Health -= 1;
if (Health <= 20) {
if (!canSeeWarnDialog) {
final AlertDialog alertDialog2 = new AlertDialog.Builder(
MainActivity.this).create();
alertDialog2.setTitle("Im hungry");
alertDialog2.setMessage("The dog health is going low "
+ "\ngive him some food");
alertDialog2.setButton("Got it",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
alertDialog2.cancel();
}
});
alertDialog2.show();
canSeeWarnDialog = true;
return;
}
}
}
}, 1000, 1000);//TimeUnit.SECONDS.toMillis(1));
答案 0 :(得分:0)
为什么不使用CountDownTimer?它似乎更适合您的任务,它会为您处理UI线程上的所有回调。
答案 1 :(得分:0)
您需要一个CountDownTimer。 以“长度”作为生命值时,以毫秒为单位(* 1000 - > 30最大生命值=> 30000长度)。当前健康状况应为millis,直至完成/ 1000。
boolean notified = false;
new CountDownTimer(length, 1000) {
@Override
public void onTick(long millisUntilFinished)
{
if(millisUntilFinished <= 20 && !notified)
{
final AlertDialog alertDialog2 = new AlertDialog.Builder(
MainActivity.this).create();
alertDialog2.setTitle("Im hungry");
alertDialog2.setMessage("The dog health is going low "
+ "\ngive him some food");
alertDialog2.setButton("Got it",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
alertDialog2.cancel();
}
});
alertDialog2.show();
notified = true;
}
}
@Override
public void onFinish()
{
//Health is 0.
notified = false; // For next time.
//if you want to restart -> retrieve full health:
this.start();
}
};