tags:

views:

1491

answers:

2
+1  Q: 

android timer

I need to display a time duration on a few of my Activities within the application. The timer starts when one of the Activity starts. Should I use service for the timer? is this the best way? or should I start thread from one of the Activity?

+1  A: 

Well, depending on how much interface work you need to display your progress, I would start a thread within the activity and then create a timer that checks the status of the thread progress and updates the interface as needed. Services are good for background tasks that don't require a lot of interface notification/updates.

Here's an example from a project I'm currently working on (UpdateListRunnable just calls "notifyDataSetChanged()" on my list adapter. I do it multiple times in the code so I encapsulated it in a class. Also, updateHandler is just a regular Handler instance):

@Override
public void run() {
    Timer updateProgressTimer = null;
    UpdateItem currentItem = null;

    for(int i = 0; i < items.size(); i++) {
        currentItemIndex = i;
        currentItem = items.get(i);

        if (currentItem.isSelected() == true) {
            updateProgressTimer = new Timer();

            updateProgressTimer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    updateHandler.post(new UpdateListRunnable());
                }
            }, 0, 2000); // check every 2 seconds

            lookupDb.downloadUpdate(currentItem);

            currentItem.setUpToDate(true);
            currentItem.setStatusCode(UpdateItem.UP_TO_DATE);
            currentItem.setProgress(0);
            updateProgressTimer.cancel();

            updateHandler.post(new UpdateListRunnable());
        } // end if its the database we are hosting on our internal server
    } // end for loop through update items

    currentItemIndex = -1;
} // end updateThread run
MattC
+2  A: 

I think in the use case you're describing it would be best to store time stamps (see Data Storage) and calculate the deltas for GUI use. If you need to display a real-time clock in one of your activities you can create a separate thread in that activity just to update the clock.

Josef