好的伙计们,我正在制作一个不断崩溃的安卓计时器应用程序。我正在使用一个计时器,它在25分钟后重置,然后重新开始。这是通过onclicklistener的开始按钮中的for循环完成的。在循环中我有另一个while循环,其中我通过语句为长类型变量赋值经过时间的值
// for循环里面的while循环内容
while(found==1){
temp = chrono.getBase() + SystemClock.elapsedRealtime();
if(temp == 25*60*1000){
found--;
}
我乘以1000因为时间是以毫秒为单位测量的?我做错了还是别的什么的。 感谢。
答案 0 :(得分:2)
while循环可能会阻塞主UI线程,直到满足条件found==1
。您可能需要的是Timer
和TimerTask
。或者,根据this article中的建议,您可以使用处理程序启动Runnable,以每50或100毫秒更新计时器时间。这是一个例子(没有经过测试和改编自linked article!):
private Handler handler = new Handler();
handler.postDelayed(runnable, 100);
private Runnable runnable = new Runnable() {
@Override
public void run() {
/* do what you need to do */
boolean isTimerReady=foobar();
/* and here comes the "trick" */
if (!isTimerReady) handler.postDelayed(this, 100);
}
};
每100毫秒开始foobar()
。 foobar()
应返回一个布尔值 - 基本上是while循环中的计算,并更新用户界面。 foobar()
返回true后,Runnable
不会重新启动。
答案 1 :(得分:0)
你正在杀死CPU,可能永远不会停止。温度恰好为25 * 60 * 1000的可能性非常低。将“==”检查更改为“> =”。另外,对于found,使用“boolean”:它更有意义。