Rocky Zhang
Rocky Zhang

Reputation: 1320

How to create a timer runed in the background and display one second of a second dynamically

How to create a timer runed in the background and display one second of a second in the TextView dynamically in MainActivity.Whatever I exit app or leaving the MainActivity,the timer also keep on.

I thinked that I can use service and BroadcastReceiver or using Handler and Thread.But I can't solve it.

Upvotes: 1

Views: 274

Answers (2)

Rocky Zhang
Rocky Zhang

Reputation: 1320

I have thinked a solution; Thread+Handler; EveryTime enter ther MainActivity we just set the time interval = EndTime-System.currentTimeMillis();

Upvotes: 0

JoeyJubb
JoeyJubb

Reputation: 2321

Having an always-on service to simply count up seconds is a bad idea, it'll waste battery life and could be killed at any time.

What you could do is something like this:

  1. Make a counter that you can start/stop with a button.
  2. On your your activity's onPause, save the System.currentTimeInMillis() along with the current count on your timer
  3. When you resume your activity, use the current System.currentTimeInMillis() value to calculate what your timer should be displaying had it been really running all that time.

Upvotes: 2

Related Questions