2012-11-24 63 views
0

任何人都可以告诉我,如果这是一件安全的事情吗?我运行一个倒数计时器(CountDownTimer),当计时器达到零时,它必须重新开始计数,例如计算一个较长的时间。要做到这一点,我打电话Android 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 
     } 
    } 

回答

0

,因为你只是更改为新的计时器,它隐含解引用以前的对象你的TableCount的单笔申报的参考你不会泄漏内存。

即使你做了奇怪的事情,比如创建一个新的计时器,每次运行并将其添加到数组(例如),你仍然不会泄漏。您最终可能会耗尽内存,但这与活动完成后的泄漏不同,并且假设您没有在其他地方持有静态引用,则会释放内存并符合垃圾回收的条件。

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

+0

谢谢 - 我做8次迭代的最大值,所以我认为,内存使用是安全的。顺便说一下,CountDownTimer似乎没有schedule()方法 - 似乎并不是太容易重置countdowntimer – mogoman

+0

对不起,我在想Timer,而不是CountdownTimer。在那种情况下,你在做什么很好。实际上,你甚至没有添加到使用的内存中。我关于循环的一点是,如果你不知道如何保持定时器的前一个实例,那么它只会使用增加的内存,而你并没有这样做。 – Simon

0

不需要重新初始化计时器.... 试试这个...

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

不起作用,调用timer.start()只是从原来的时间开始,而不是从下次开始 – mogoman

-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(); 
+0

你可以改变onFinish()的时间,例如'count = new ServiceCount((long)(2 * 60 * 1000), 1000); // 2分钟' –

+0

是的,你是对的,但你的例子与问题中的完全相同。问题是,我正在做什么(事实上你的代码在做什么)可以被视为从内存泄漏的角度来看是“安全的” - 正如我所提到的,我的代码可以100% – mogoman