tags:

views:

79

answers:

2

I'm re-inventing the wheel here, but as I'm a beginner programmer I'm curious as to the best way to do this...

As part of an Android app, I'm developing a very simple media player. It plays the file, and I want a m:s timer, so the user can see how far into the file they are (e.g. "04:56"). I'm probably missing the obvious, but what's the best way to do this?

One way would be to generate a new thread which sleeps for 1000ms, then calls MediaPlayer.getCurrentPosition() and updates the UI. However, this seems slightly ridiculous - my thread isn't guaranteed to come back every second, so I'm going to be displaying an inaccurate time. There must be a better way of doing this?

Educate me (or link for me).

A: 

One alternative might be to start an independent timer when the music starts. Have it "sync" by calling MediaPlayer.getCurrentPosition() once every five seconds or so to ensure that the time remains accurate.

Dave Swersky
+1  A: 

Just use Handler#postDelayed() or View#postDelayed() to do your once-a-second updates. This saves you from having to fork a thread, let alone clean up after it.

Here is a project using that specific technique for your desired purpose: updating a time counter based on MediaPlayer progress.

CommonsWare
Thanks for this example - very useful!It got me thinking though... suppose I were writing an alarm clock program, which displays an alarm to wake up me up at 7am; what would be the most efficient way of that? Is sleeping and checking every second really done by all apps that do things like this?
Chris
For an alarm clock, I would use AlarmManager. That way, you will get control at the desired time even if your app is not presently running. However, AlarmManager is not designed for check-every-second scenarios such as your MM:SS counter.
CommonsWare