0

How to create a countdown timer that stops and "waits" when the screen is off, resumes when back on.

Just like the title says, how to program a basic countdown timer in Android Studio that stops when the user closes the phone, (screen is off), and restarts when the screen turns back on. Still a complete noob at this and I would just need basic code that works and does this.

Thanks

I already have a basic interface...

2 Answers2

0

Use a Handler with a Runnable, which is called every second.

Handler handler = new Handler();
int countdown = 300; // set countdown value in seconds
Runnable countdownRunnable = new Runnable() {
    @Override
    public void run() {
        countdown--;

        if(countdown == 0) {
            // countdown finished
        } else {
            handler.postDelayed(this, 1000);
        }
    }
}

First, start the countdown with handler.post(countdownRunnable). In the Activity/Fragment onStop(), remove the runnable from the handler with handler.removeCallbacks(countdownRunnable);, and add it again in onStart() with handler.post(countdownRunnable).

Also, don’t forget to save and restore the state (current countdown value).

patloew
  • 1,090
  • 9
  • 13
0

As Nacho L. Answered On Stackoverflow For screen on-off state, you can try with ACTION_SCREEN_ON and ACTION_SCREEN_OFF Intents, as shown in this blog post: [http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/2

Community
  • 1
  • 1
Wais
  • 1,739
  • 1
  • 13
  • 13