tags:

views:

23

answers:

1

My activity contains data retrieved from internet. I want the activity to automatically refresh its content every 5 minute. What is the best way to implement it? Should I use java's Timer and TimerTask?

Thanks.

+1  A: 

You need to setup an alarm to fire at regular interval, and once the alarm fires(broadcastreceiver) make sure it calls notifiyDataSet on your adapter, so the system will automatically rebuild your listview (if you are using one)

This is a sample code to setup an alarm to fire X minutes from now

Intent intent = new Intent(this, WeatherRefreshService.class);
PendingIntent sender = PendingIntent.getService(this, 0, intent, 0);

// We want the alarm to go off 60 seconds from now.
long firstTime = SystemClock.elapsedRealtime();
firstTime += REPEATING_ALARM_INTERVAL_IN_MINUTES * 60 * 1000;

// Schedule the alarm!
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,
        REPEATING_ALARM_INTERVAL_IN_MINUTES * 60 * 1000, sender);

This example uses a PendingIntent for a Service, but you can change that to a broadcast if you like too.

Pentium10
Thanks for you reply. Very useful.Another question, how is this approach compared with Timer and TimerTask? Can I use Timer and Timer Task?
I would not recommend, the OS might close your activity to free up some memory space, so your timer will shut down. The alarm will still keep firing if the OS garbage collected your app.
Pentium10