How to start a service at a specific time

无人久伴 提交于 2019-12-08 03:56:14

问题


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);
}

回答1:


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



回答2:


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.


来源:https://stackoverflow.com/questions/24822506/how-to-start-a-service-at-a-specific-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!