Search code examples
androidtimersharedpreferencescountdown

CountDown Timer value to be stored in shared preference


Sorry if i didn't write a suitable title for my problem. I am developing an android game in which i had to start count down timer from 10 minutes. The value to be stored in textView Now my textView is showing the countdown value i.e it starts from 09:59 and decreasing second by second but obviously when i close the application and then restart its gone. This should be saved via shared preference but Iam confused how to used shared preference in it. i.e. if i close the app when 07:45 minutes left and preference is saved then when i will return and restart the app after 2 minutes then it should show 05:45 minutes left then how can i get that? because if I subtract the countdown time from system time then it may be not the result that i wanted because system time is in hour format and iam using minute and second only.

Here is the code before oncreate

MyCounter timer = new MyCounter(600000,1000);
private static final String FORMAT = "%02d:%02d";

and this is what iam using to get the countdown timer in textview

public class MyCounter extends CountDownTimer{

        public MyCounter(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            datetime.setText("Timer Completed,Now you can play");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            datetime.setText(""+String.format(FORMAT,

TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
                    TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
  TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
                      TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));

        }
    }

Any link to specific code and shared preference example using countdown will help me a lot


Solution

  • Create an alarm set method, this is used to set/start alarm.

    public void SetAlarm(Context context){ 
        AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, TenMinuteTimer.class);   
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,  intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),10*60*1000, pendingIntent);  
    }
    

    Cancel the alarm, this method is used to remove the alarm once it has been reached

    public void CancelAlarm(Context context){
        AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, TenMinuteTimer.class);   
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,  intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmMgr.cancel(pendingIntent);
    }
    

    Save when the alarm completed those 10 minutes:

    public class TenMinuteTimer extends BroadcastReceiver{
    
    @Override
    public void onReceive(Context context, Intent intent) {
        //Save, timer has completed.
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(); 
        prefs.edit().putBoolean("timerCompleted", true).commit();
    
        //cancel the Alarm, no need for repeating (right?)
        CancelAlarm(this);
    }
    

    Add to your Manifest.XML:

     <receiver 
         android:name=".TenMinuteTimer"
         android:enabled="true"
         android:process=":remote"> 
     </receiver>
    

    Start/Set your alarm whenever you want, by calling the SetAlarm(this) method

    Check , when a user starts your application again just check if timer has completed by adding to your onCreate() :

    Boolean usetTimerCompleted = prefs.getBoolean("timerCompleted", false);  //False if not yet saved (first time), or timer is not yet completed
    
    if (usetTimerCompleted){
    // User Timer is completed, now do something
    }
    

    This should work, If I did something wrong, please edit my post, or comment below.

    I didn't test this out!