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


how create countdown timer stops , "waits" when screen off, resumes when on.

just title says, how program basic countdown timer in android studio stops when user closes phone, (screen off), , restarts when screen turns on. still complete noob @ , need basic code works , this.

thanks

i have basic interface...

use handler runnable, 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 countdown handler.post(countdownrunnable). in activity/fragment onstop(), remove runnable handler handler.removecallbacks(countdownrunnable);, , add again in onstart() handler.post(countdownrunnable).

also, don’t forget save , restore state (current countdown value).


Comments