0

as always Thanks for reading and thinking on this question.

I want to save elapsed time in some activities and using them later, i thought SharedPreferences would be a good choice for saving, but i found Using Chronometer not efficient. I'll appreciate any help. thanks.

mazhar
  • 180
  • 1
  • 11

1 Answers1

0

Declare your variable:

long lastTimeRecorded;

Then in onCreate get a start time:

lastTimeRecorded = System.currentTimeMillis();

Then when you update the time call this function from the activity:

public void updateTimer(){

long elapsedTime = System.currentTimeMillis() - lastRecordedTime;
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.edit().putLong("elapsedTime", elapsedTime);
}

If you want it to repeat at certain intervals:

private final int interval = 1000; // in millis
private Handler handler = new Handler();
private Runnable runnable = new Runnable(){
    public void run() {
        updateTimer();
    }
};
...
handler.postAtTime(runnable, System.currentTimeMillis()+interval);
handler.postDelayed(runnable, interval);

From samuel, here How to set a timer in android

Community
  • 1
  • 1