Search code examples
androidcountdowntimer

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?


Solution

  • 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