2013-08-07 26 views
1

我需要在健康狀況低於20或等於20後顯示「alertDialog」,我在代碼中沒有任何錯誤後每秒鐘健康狀況降低「1」 。問題是「健康」通過邊界/限制應用程序粉碎後,粉碎,我不知道爲什麼會發生這種情況,有沒有人來幫助我呢? 我還確保有是「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)); 
+1

您無法從非UI線程afaik中顯示對話框。使用不同的方法(可能是:['Handler'](http://developer.android.com/reference/android/os/Handler.html))或者通過'runOnUiThread'啓動一個單獨的可運行程序。 – dst

+1

dst可能有正確的答案。但是,請不要在沒有發佈logcat中的堆棧跟蹤的情況下詢問崩潰 - 如果沒有這些,我們很少會解決它。 –

回答

0

你爲什麼不使用CountDownTimer?它看起來更適合你的任務,它會爲你處理UI線程中的所有回調。

+0

結束後它會從頭開始自動啓動? 也仍然是粉碎:/ – Stefan

+0

有沒有人可以幫助我做出一個非常簡單的計時器/處理程序或任何其他健康狀況將下降「1」,當健康狀況將下降20或20以下顯示alertDialog或打開手機報警或做任何事情通知玩家?謝謝:) – Stefan

+0

@Stefan,CountDownTimer不會自動重啓。你可以重新創建它。 –

0

您需要一個CountDownTimer。 當以「毫秒」爲單位生效時,「長度」爲
(* 1000 - > 30最大健康狀況=> 30000長度)。當前健康狀況應爲毫秒級完成/ 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(); 
    } 
}; 
+0

如果你想重新啓動,我不會得到這個?我只需要把'健康= 100;'? – Stefan

+0

我的建議是使用millisUntilFinished作爲健康。並將健康提升到100意味着重新啓動定時器。或this.start(); – user2558461

+0

哦,我明白了,但我並不真的需要我需要當健康是20或低於你需要飼料的「狗」和健康大於20,但計時器仍然計數,直到健康0狗去死...希望你能理解我:) 編輯:也我想這個動作去每2分鐘... – Stefan