Ooto
Ooto

Reputation: 1247

CountdownTimer: How to restart from a remaining time when the user goes back to the previous activity?

I'm beginner in Android and it might be really basic question. I'm trying to create a CountDownTimer which keeps countdown between two activities. Users can go to the Activity B and go back to Activity A from Activity B. And I am thinking of saving the remaining time in SharedPreferences. What I want to know is when the user does OnBackPressed and save the current remaining time into SharedPreferences and goes back to the previous activity, how can I restart the countdown timer from the remaining time in previous activity?

Upvotes: 1

Views: 109

Answers (2)

Abdul Waheed
Abdul Waheed

Reputation: 4678

To get this, you must have a separate thread to calculate count down stuff and it will be running all way weather you are at on Activity 1 or another activity. And that thread should update the activity(Check if activity is visible). To update the activity there can be various way.

  1. You can use thread and update the activity via broadcast
  2. You can use thread and check for the activity visibility, if that is visible do the stuff accordingly.
  3. As you are already using shared preference, you can achieve the same thing via shared preference as well. You can use thread/service and update the shared preference on every tick or every second. And when you get onResume call back of the activity. get the value back from shared preference and use it accordingly.

Hope this will help you.

Upvotes: 0

clauub
clauub

Reputation: 1160

I think this method should help you:

@Override
public void onResume() { // This will be trigger when your activity is created or come to front
    // Load preference
    // Start timer
}

@Override
public void onStop() { // This will be triggered when your activity goes behind or before your activity destroyed.
   // Cancel timer
   // Save preference
}

It's really simple, just follow the comments. Let me know if this helps

Upvotes: 1

Related Questions