1

Am creating an application that fetch data from webservice. I have been while(true) and sleeping the loop at a specific milliseconds.. i had like to make the service action(fetching data from webservice) to always start at a specific time.. instead on being on always and pausing by Thread.sleep(milli)... Thanks this is what have been using

while(true)
{
///pullDataFromWebservice();
Thread.sleep(600000);
}
heeleeaz
  • 172
  • 1
  • 2
  • 13
  • 1
    this link maybe can help you: http://stackoverflow.com/questions/3052149/using-alarmmanager-to-start-a-service-at-specific-time – hqt Jul 18 '14 at 10:14

2 Answers2

2

Use the Alarm API. It is way safer than having a sleep & poll service.

Why?

Because Android is very likely to reclaim such a long running services when resources turn low, resulting in your delayed logic never being called!


An example for activating a callback in 1 hour from now:

private PendingIntent pIntent;

AlarmManager manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, MyDelayedReceiver.class);  <------- the receiver to be activated
pIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime() +
        60*60*1000, pIntent);  <---------- activation interval
Gilad Haimov
  • 5,672
  • 2
  • 24
  • 30
  • Very helpful. really saved me time. the 'PendingIntent.getBroadcast(context, 0, intent, 0)' will it be sending a broadcast?? – heeleeaz Jul 18 '14 at 11:12
  • the pending intent wraps that intent that will be used by the alarm manager to wake up your receiver at due time – Gilad Haimov Jul 18 '14 at 11:16
  • i meant, other context have to receive the broadcast sent by The AlarmManager?? i can also use 'PendingIntent.getService(this, 0, intent, 0)' to start the service instead of sending a broadcast ?? – heeleeaz Jul 18 '14 at 11:21
  • I have successfully scheduled ,but Consider a situation,if the app is cleared by task manager,does the schedule still works? – guru_007 Jul 11 '17 at 11:01
0

Try using AlarmManager - A bit battery eater though

AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

Intent intent = new Intent(this, YourClass.class);
PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

Calendar cal= Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 19);
cal.set(Calendar.MINUTE, 20);
cal.set(Calendar.SECOND, 0);

alarmMgr.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pIntent);

//RTC_WAKEUP to enable this alarm even in switched off mode.
Arun Shankar
  • 2,443
  • 2
  • 24
  • 36