2

My Android app has a TextView telling the user the data age ("13 minute ago"). I currently update this every second using a Runnable to catch when the minute changes with a notifyDataSetChanged() to my adapter. But this is causing garbage collection every second...

Is there another method to trigger a TextView update (or take general action) when the system clock changes minute without checking every second for such a change?

mraviator
  • 4,034
  • 9
  • 38
  • 51
  • Why dont you simply spread out your counter / timer to trigger every 30 seconds or so (instead of 1), the most you will ever be behind is 29 seconds. – trumpetlicks Jan 29 '13 at 18:44
  • It crossed my mind. I guess I don't like it when the system clock (visible to the user) flips a minute and the age in the ListView does not. Picky, I know... – mraviator Jan 29 '13 at 18:45

4 Answers4

6

Since you already set up a Runnable and callback, use modulo to calculate when the next update should happen:

handler.postDelayed(runnable, 
        DateUtils.MINUTE_IN_MILLIS - System.currentTimeMillis % DateUtils.MINUTE_IN_MILLIS);

This will run the callback when the next minute occurs whether it is 59, 30, or 1 second(s) away. As a note, if the Runnable only updates one TextView don;t forget to switch to DateUtils.HOUR_IN_MILLIS when the event is an hour old, no sense updating "1 hour ago" every minute.

You may find methods like DateUtils.getRelativeTimeSpanString() useful for creating the "x minutes ago" strings.

Sam
  • 86,580
  • 20
  • 181
  • 179
4

While Sam's answer is perfectly good, I'm just adding this because it fits the question so perfectly. There is actually a broadcast sent by the system every minute when the clock changes. It is Intent.ACTION_TIME_TICK and you can only receive it using a BroadCastReceiver that was registered manually in your code, not through the manifest. See the documentation here.

Thrakbad
  • 2,728
  • 3
  • 23
  • 31
  • That's actually very handy too. I'll have to take a closer look at it. Thanks! – mraviator Jan 29 '13 at 20:06
  • This is answered here - https://stackoverflow.com/questions/28934625/android-listener-that-detects-minute-changing-in-the-clock/44192366 – Smeet Jun 22 '21 at 06:17
0

User the Timer object with fixed period.

The methods take a TimerTask object.

See the Timer documentation from google

REMEMEBER to cancel the timer when stopping the activity

Moog
  • 10,193
  • 2
  • 40
  • 66
0

There is prettier solution for this besides Sam's great answer.

Make use of http://developer.android.com/reference/android/text/format/DateUtils.html to find the time span and register for android.intent.action.TIME_TICK where you'll be updating the time in the listview.

Here is another same question and answer

Smeet
  • 4,036
  • 1
  • 36
  • 47
Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148