Бесконечный таймер обратного отсчета - PullRequest
0 голосов
/ 16 марта 2012

Здесь у меня есть CountDownTimer, который я хочу запустить и перезапустить в бесконечном цикле, и я не знаю, почему он не работает:

 prefs = PreferenceManager.getDefaultSharedPreferences(this);

   xtime = System.currentTimeMillis()-prefs.getLong("time",System.currentTimeMillis());      

   timer=24000-(xtime+prefs.getLong("time2",0)); 

   final SharedPreferences.Editor editor = prefs.edit();
   editor.putLong("time2",xtime+prefs.getLong("time2",0));  

   editor.commit(); 

   new CountDownTimer(timer, 1000) { 

     public void onTick(long elapsed) {

        long timer2=elapsed;
        hours = timer2 / hours_in_millies;
        timer2 %= hours_in_millies;
        minutes = timer2 / minutes_in_millies;
        timer2 %= minutes_in_millies;
        Log.v(TAG, "seconds" + seconds);
        if(seconds<10)
            seconds=timer2/1000;   
        else 
        seconds = timer2 / seconds_in_millies;

        if(seconds<10)
        seconds=timer2/100;   

        if(seconds>1&&seconds<2)                
        seconds=0;

          if(hours>=10&&minutes>=10&&seconds>=10)
           time.setText(hours + ":" + minutes + ":" + seconds);
             else 
                 if (hours<10&&minutes>=10&&seconds>=10)
                 time.setText("0"+hours + ":" + minutes + ":" + seconds);            
                else 
                    if (hours<10&&minutes<10&&seconds>=10)
                    time.setText("0"+hours + ":0" + minutes + ":" + seconds);
                else 
                    if (hours>=10&&minutes<10&&seconds<10)
                    time.setText("0"+hours + ":0" + minutes + ":0" + seconds);
                else 
                    if(hours>=10&&minutes>=10&&seconds<10)
                         time.setText(hours + ":" + minutes + ":0" + seconds);
                else 
                        if (hours>=10&&minutes<10&&seconds<10)
                         time.setText(hours + ":0" + minutes + ":0" + seconds);
                        else 
                            if(hours>=10&&minutes<10&&seconds>=10)
                             time.setText(hours + ":0" + minutes+":" + seconds);
                            else if(hours<10&&minutes>=10 && seconds<10)
                                 time.setText("0"+hours + ":" + minutes +":0"+ seconds);


     }

     public void onFinish() 
     {  editor.clear();            
        this.start();
     }

  }.start();

     xtime=System.currentTimeMillis(); 
     SharedPreferences.Editor editor2 = prefs.edit();
     editor2.putLong("time",xtime);         
     editor2.commit(); 

}

SharedPreferencesпомогает мне восстановить CountDownTimer с того момента, когда действие завершилось с использованием моего алгоритма.Проблема в том, что даже если я вызываю this.start () в моем OnFinish (), я получаю эту ошибку NullPointerException в строке с this.start.Буду признателен за помощь.Спасибо!PS: у меня тоже проблема, когда таймер опускается ниже 10 секунд, после этого появляются следующие цифры, но с бонусной цифрой.(95,85,75 ... 15).Если в моем:

  if(seconds<10)
        seconds=timer2/1000;   
    else 
    seconds = timer2 / seconds_in_millies;

я бы изменил секунды = timer2 / 1000 с timer2 / 10000, он вообще не показывает цифры и останавливается на 10.

Ответы [ 2 ]

1 голос
/ 16 марта 2012

Вы можете сделать это ..

у вас на работе

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

 Date date = (Date)settings.getString("date",0);
 Calendar c = Calendar.getInstance(); 
        Date d=c.getTime();
long diffInMs = d.getTime() - date.getTime();
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMis);
if (diffInSec>86400)
{
 SharedPreferences myPrefs = this.getSharedPreferences("PREFS_NAME",0);
SharedPreferences.Editor ed = myPrefs.edit();
ed.putString("Date", String.valueOf(d));
ed.commit();
  //allow your activity to open
}
 else
{
 counter= new MyCount(diffInSec*1000,1000);
 counter.start();
 }

MyCount класс

 public class MyCount extends CountDownTimer{
 public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
    Intent k=new Intent(Myactivity.this,Myactivity.class);
                 startActivity(k);
}
@Override
public void onTick(long millisUntilFinished) {
    s1=millisUntilFinished;
     <---- display s1/1000 to show number of seconds left

}
}

}

надеюсь, что это работает ..

1 голос
/ 16 марта 2012

это дает вам бесконечный таймер обратного отсчета ... 30 секунд ... вы можете подсчитать, сколько раз был создан новый таймер, чтобы получить общее время истекшее .. как это

MyCount counter;
counter=new MyCount(30000,1000);
  counter.start();

MyCount класс

public class MyCount extends CountDownTimer{
    public MyCount(long millisInFuture, long countDownInterval) {
    super(millisInFuture, countDownInterval);
    }
    @Override
    public void onFinish() {
        counter= new MyCount(30000,1000);
     counter.start();
     n=n+1;
    }
    @Override
    public void onTick(long millisUntilFinished) {
        s1=millisUntilFinished;
        r1=(30000-s1)/1000;


    }
    }



   }

чтобы узнать общее время ...

int time=(n*30)+r1;<--- total time elapsed..

чтобы приостановить использование таймера

counter.cancel();

для возобновления использования

counter= new MyCount(s1,1000);
     counter.start();
...