2

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.

user256239
  • 17,717
  • 26
  • 77
  • 89
  • hi if the below answer is able to solve the problem then can u provide the source code coz me getting stuck on same problem... & it's highly important.... :) – Sumant Mar 22 '11 at 10:13
  • [Try this][1] It is working fine to me. [1]: http://stackoverflow.com/questions/6134832/auto-refresh-the-activity/6840666#6840666 – vijay Nov 03 '14 at 04:53

1 Answers1

1

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
  • 204,586
  • 122
  • 423
  • 502
  • Thanks for you reply. Very useful. Another question, how is this approach compared with Timer and TimerTask? Can I use Timer and Timer Task? – user256239 Jul 09 '10 at 23:49
  • 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 Jul 10 '10 at 18:06