Java Android自定义数字时钟,循环运行时出错“;未处理的异常类型InterruptedException“;
我正在android上构建一个简单的Java Android自定义数字时钟,循环运行时出错“;未处理的异常类型InterruptedException“;,java,android,loops,Java,Android,Loops,我正在android上构建一个简单的时钟 我的问题是在while循环中,当我使用Thread.sleep(5000)时,我得到错误:“未处理的异常类型InterruptedException” 如何运行循环以使其正常工作?没有太多的代码行,所以我完全复制了它,希望能对某些人有用,因为我还没有找到很多时钟的例子 public class MainActivity extends Activity { TextView hours; TextView minutes; Cal
时钟
我的问题是在while循环中,当我使用Thread.sleep(5000)
时,我得到错误:“未处理的异常类型InterruptedException
”
如何运行循环以使其正常工作?没有太多的代码行,所以我完全复制了它,希望能对某些人有用,因为我还没有找到很多时钟的例子
public class MainActivity extends Activity {
TextView hours;
TextView minutes;
Calendar c;
int cur_hours;
int cur_minutes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clock_home);
hours = (TextView) findViewById(R.id.hours);
minutes = (TextView) findViewById(R.id.minutes);
while (true) {
updateTime();
Thread.sleep(5 * 1000); // Unhandled exception type InterruptedException
}
}
public void updateTime() {
c = Calendar.getInstance();
hours.setText("" + c.get(Calendar.HOUR));
minutes.setText("" + c.get(Calendar.MINUTE));
}
}
抛出InterruptedException,您需要捕获(或)重试
将Thread.sleep调用包装到try/catch
例如:
try
{
Thread.sleep(5 * 1000);
}catch(InterruptedException ie)
{
//Log message if required.
}
编辑:
作为
当线程正在等待、休眠或以其他方式暂停某个线程时引发
长时间,另一个线程使用中断方法中断它
课堂线程
在什么情况下会抛出该异常?谢谢,我也这么认为。OP的设计显然有缺陷,但我目前没有一个解决方案来评论。@JonathonReinhart:我明白你的意思,同意。OP,若你们正在寻找简单的时钟,我想在互联网上有一些例子,最好用它们来代替重新设计。我只找到了sdk提供的digitalClock和textClock视图的示例。但它们很难定制。updateTime()可以工作,我只是不知道如何每隔几秒钟运行一次。你有什么想法吗?