共享首选项和倒数计时器 [英] SharedPreferences and Countdown Timer

查看:88
本文介绍了共享首选项和倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将CountDown Ttimer值保存到一个变量中,以便下次用户启动Countdowntimer Activity时,它将在剩余的确切经过时间重新加载。
这是我的代码,我不明白为什么它不起作用。 (它显示我的时间文本框为空)

I want to save the CountDown Ttimer value into a variable so that next time the user start the Countdowntimer Activity, it to reload at the exact elapsed time as it remained. Here is my code and I don't understand why it doesn't works. (it shows my time Textbox empty)

prefs = PreferenceManager.getDefaultSharedPreferences(this);
   long timer = prefs.getLong("TIME", 86400000);

   new CountDownTimer(timer, 1000) {

         public void onTick(long elapsed) {
             System.out.print(elapsed);
             long timer2=elapsed;
             long hours = timer2 / hours_in_millies;
             timer2 %= hours_in_millies;
             long minutes = timer2 / minutes_in_millies;
             timer2 %= minutes_in_millies;
             long seconds = timer2 / seconds_in_millies;
             time.setText(hours + ":" + minutes + ":" + seconds);
             SharedPreferences.Editor editor = prefs.edit();
             editor.putLong("TIME",elapsed);
             editor.commit(); 


         }


推荐答案

已解决:

  prefs = PreferenceManager.getDefaultSharedPreferences(this);

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

   long timer=86400000-(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) {

             Log.d(TAG, "TIMER" + System.currentTimeMillis());
             long timer2=elapsed;
             long hours = timer2 / hours_in_millies;
             timer2 %= hours_in_millies;
             long minutes = timer2 / minutes_in_millies;
             timer2 %= minutes_in_millies;
             long seconds = timer2 / seconds_in_millies;
             time.setText(hours + ":" + minutes + ":" + seconds);


         }

         public void onFinish() 
         { Intent intent = new Intent(Hug.this, Hug_Accepted.class);
        startActivity(intent);

         }

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

}

这篇关于共享首选项和倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆