服务中的定时器功能(计时器的种类)

时间:2013-04-02 07:55:14

标签: android service timer stopwatch chronometer

我的目的是创建一个从00:00:00开始并与录音功能一起挂起的计时器。此录制在服务中完成,因此,计时器也在同一服务中。如果应用程序移动到后台,则录制和计时器继续运行,应用程序使用myService.getTime()在onResume上选择时间。

但我经历了两件奇怪的事情。 第一个是我的计时器有时会比第二个更快,有时更慢,有时会从00:00:04跳到00:00:06等等。没有任何一致性在里面。我使用下面的代码,但可能有更好的选择来解决这个问题? 第二个是因为我在按钮中导致延迟,但是我在服务中启动了它?

SERVICE

//////////TIMER FUNCTION START//////////

        private void startTimerClick() {

            if (stopped) {
                startTime = System.currentTimeMillis() - elapsedTime;
            } else {
                startTime = System.currentTimeMillis();
            }
            mHandler.removeCallbacks(startTimer);
            mHandler.postDelayed(startTimer, 0);

        }

        private void pauseTimerClick() {
            mHandler.removeCallbacks(startTimer);
            stopped = true;

        }

        private void stopTimerClick() {
            mHandler.removeCallbacks(startTimer);
            stopped = false;

        }

        private void startTimer() {

            startTimer = new Runnable() {
                public void run() {
                    elapsedTime = System.currentTimeMillis() - startTime;
                    updateTimer(elapsedTime);
                    mHandler.postDelayed(this, REFRESH_RATE);
                }
            };

        }

        private void updateTimer(float time) {
            secs = (long) (time / 1000);
            mins = (long) ((time / 1000) / 60);
            hrs = (long) (((time / 1000) / 60) / 60);

            /*
             * Convert the seconds to String and format to ensure it has a leading
             * zero when required
             */
            secs = secs % 60;
            seconds = String.valueOf(secs);
            if (secs == 0) {
                seconds = "00";
            }
            if (secs < 10 && secs > 0) {
                seconds = "0" + seconds;
            }

            /* Convert the minutes to String and format the String */

            mins = mins % 60;
            minutes = String.valueOf(mins);
            if (mins == 0) {
                minutes = "00";
            }
            if (mins < 10 && mins > 0) {
                minutes = "0" + minutes;
            }

            /* Convert the hours to String and format the String */

            hours = String.valueOf(hrs);
            if (hrs == 0) {
                hours = "00";
            }
            if (hrs < 10 && hrs > 0) {
                hours = "0" + hours;
            }


        }
        //////////TIMER FUNCTION END////////////


    public String getHours(){

        return hours;
    }

    public String getMinutes(){

        return minutes;
    }

    public String getSeconds(){

        return seconds;
    }
}

活性(/片段)

private void timerStart() {

        handler = new Handler();
        Thread t = new Thread() {

              @Override
              public void run() {
                try {
                  while (!isInterrupted()) {
                    Thread.sleep(1000);
                    handler.post(new Runnable() {
                      @Override
                      public void run() {

                          timer.setText(myService.getHours()+":"+myService.getMinutes()+":"+myService.getSeconds());
                      }
                    });
                  }
                } catch (InterruptedException e) {
                }
              }
            };

            t.start();

    }

1 个答案:

答案 0 :(得分:0)

您在服务和活动/片段代码中都使用了线程。 在Android中使用线程进行时间敏感的任务是一个问题,因为Android能够显着延迟线程。

我一直在使用ScheduledThreadPoolExecutor进行类似的任务,效果很好。

您正在使用它:

ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1); // where 1 is the number of needed concurrent threads. 1 should last for your needs.
executor.scheduleWithFixedDelay(new TimerTask() {  
    // your recurringly executed code here
}, 0, 1, TimeUnit.SECONDS);