简体   繁体   English

在java / android +崩溃应用程序中的时间

[英]Time in java/android + crashing app

OK guys, I am making an android timer app which keeps crashing. 好的伙计们,我正在制作一个不断崩溃的安卓计时器应用程序。 I am using a chronometer which resets when it reaches 25 minutes and then starts again. 我正在使用一个计时器,它在25分钟后重置,然后重新开始。 This is being done by a for loop in the start button onclicklistener. 这是通过onclicklistener的开始按钮中的for循环完成的。 In the loop i have another while loop in which i assing a long type variable the value of elapsed time by the statement 在循环中我有另一个while循环,其中我通过语句为长类型变量赋值经过的时间

// Contents of while loop inside for loop // for循环中while循环的内容

 while(found==1){
                temp = chrono.getBase() + SystemClock.elapsedRealtime();
                if(temp == 25*60*1000){
                    found--;
                }

I multiplied by 1000 because time is measured in milliseconds? 我乘以1000因为时间是以毫秒为单位测量的? Am i doing this wrong or is it something else. 我做错了还是别的什么的。 Thanks. 谢谢。

The while loop probably blocks the main UI thread until the condition found==1 is met. while循环可能会阻塞主UI线程,直到found==1条件found==1 What you probably need is a Timer and a TimerTask . 您可能需要的是TimerTimerTask Or, as recommended in this article , you can start a Runnable using a handler to update the chronometer time every 50 or 100 msec. 或者,按照本文的建议,您可以使用处理程序启动Runnable,以每50或100毫秒更新计时器时间。 Here is an example (not tested and adapted from the 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);
   }
};

This starts foobar() every 100 msec. 这每100毫秒开始foobar() foobar() should return a boolean value - basically the calculations in your while loop, and update the user interface. foobar()应该返回一个布尔值 - 基本上是你的while循环中的计算,并更新用户界面。 Once foobar() returns true, the Runnable is not restarted. 一旦foobar()返回true, Runnable就不会重新启动。

You are killing the CPU, and probably never stopping. 你正在杀死CPU,可能永远不会停止。 The likelihood of temp being EXACTLY 25 * 60 * 1000 is very low. 温度恰好为25 * 60 * 1000的可能性非常低。 Change that "==" check to ">=". 将“==”检查更改为“> =”。 Also, use a "boolean" for found: it makes more sense. 另外,对于found,使用“boolean”:它更有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM