1

在健康低于 20 或等于 20 后,我需要使健康每秒下降“1”以显示“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));
4

2 回答 2

0

你为什么不使用CountDownTimer?它似乎更适合您的任务,它为您处理 UI 线程上的所有回调。

于 2013-08-07T17:36:48.497 回答
0

你需要一个倒数计时器。当将“长度”作为以毫秒为单位的生命值时
(* 1000 -> 30 最大生命值 => 30000 长度)。当前生命值应为 millisUntilFinished/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();
    }
};
于 2013-08-07T18:38:29.553 回答