Android CountDownTimer范围

时间:2012-11-24 10:23:58

标签: java android countdown

有谁能告诉我这是否安全?我运行一个倒数计时器(CountDownTimer),当计时器到达零时,它必须重新开始,倒计时,例如,更长的时间。要做到这一点,我打电话

timer = new TableCount(nextTime * 1000, 100);

在onFinish()方法中。

它运行没有问题,但我担心它可能会导致内存泄漏。我是否应该让计时器发出某种通知,表明它已经完成了?以下是活动代码中的重要部分:

public class TableActivity extends Activity {
    TableCount timer; // the count down timer
    protected int nextTime;
    ...
    // somewhere I call this - user clicked the "start" button
    timer = new TableCount(nextTime * 1000, 100);
    nextTime += 100; // for example
    ...
    public class TableCount extends CountDownTimer
    {
        public void onFinish() {
            ... // check if number of iterations has been reached, else:
            // start counting down from the next value
            timer = new TableCount(nextTime * 1000, 100);
            nextTime += 100; // for example
        }
    }

3 个答案:

答案 0 :(得分:0)

您不会泄漏内存,因为您只是将TableCount的单个声明的引用更改为新的计时器,该计时器隐式取消引用前一个对象。

即使你做了一些奇怪的事情,比如每次运行创建一个新的计时器并将其添加到一个数组(例如),你仍然不会泄漏。你可能最终会耗尽内存,但这与漏活不同,因为当活动结束时(),并假设你没有在其他地方持有静态引用,那么内存被释放并有资格进行垃圾收集。

但是,为什么不重用现有的计时器并使用schedule()再次运行它?

答案 1 :(得分:0)

不需要再次初始化计时器.... 试试这个......

   int temp=nexttime;
   public class TableCount extends CountDownTimer
   {
       public void onFinish() {
       nexttime=temp;
       timer.start();
       }
   }

答案 2 :(得分:-1)

public class ServiceCount extends CountDownTimer
{
    public ServiceCount(long millisInFuture, long countDownInterval)
    {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onFinish()
    {
             count = new ServiceCount((long) (1 * 60 * 1000), 1000); // 1 minute
             count.start();
    }

    @Override
    public void onTick(long millisUntilFinished)
    {
        Log.d("timer", "" + millisUntilFinished / 1000);
    }
}

ServiceCount count = new ServiceCount((long) (1 * 60 * 1000), 1000); // 1 minute
count.start();