2015-06-20 107 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

会尝试告诉你;) –

相关问题