2015-06-20 102 views
0

我做了一個被稱爲每1秒和函數中我寫爲什麼button.setText()顯示錯誤

myButton.setText("Stop"); 

現在的一切,而不該代碼的偉大工程的功能,但每當我寫這篇文章的代碼,移動我讓我的測試顯示消息「應用程序已停止工作」 我一直在尋找解決方案3天現在,幫助將不勝感激!

這是我的代碼

check_time = new TimerTask() { 
@Override 
         public void run() { 

           myButton.setText("Stop"); 

          Calendar lo_Calender = Calendar.getInstance(); 
          int current_h = lo_Calender.get(Calendar.HOUR); 
          int current_m = lo_Calender.get(Calendar.MINUTE); 
          if (H_toWake == current_h && M_toWake == current_m) { 
           out.println("ring"); 

           alarm(); 

           //return; 
          } else { 
           out.println("no ring!"); 
          } 
         } 
        }; 
        time.schedule(check_time, 0, 1000); 
} 

回答

4

您不能從後臺線程觸摸UI。使用AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html

+0

會試着告訴你;) –

+0

對不起,但我應該使用包括定時函數還是(myButton.setText(「Stop」))到AsyncTasked類中? –

+0

參考這個答案http://stackoverflow.com/questions/22890505/running-an-async-task-inside-a-timer-in-android – Helmi

1

首先 - 確切的錯誤應該在你的logcat中。它會告訴你發生了什麼問題。首先看看你自己。

在這個特定的情況下 - TimerTasks作用於一個單獨的線程。您只能在UI線程上更改UI。把這部分放在runOnUiThread塊中,你會沒事的。

+0

會嘗試告訴你;) –

相關問題