问题描述
我正在创建一个从网络服务获取数据的应用程序.我一直 while(true)
并在特定的毫秒内睡眠循环..我想让服务操作(从 webservice 获取数据)总是在特定时间开始......而不是在总是和由 Thread.sleep(milli)
暂停...谢谢这是一直在使用的
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)
... Thanksthis is what have been using
while(true)
{
///pullDataFromWebservice();
Thread.sleep(600000);
}
推荐答案
使用 警报 API. 这比睡眠和睡眠要安全得多.投票服务.
Use the Alarm API. It is way safer than having a sleep & poll service.
为什么?
因为 Android 很可能在资源变少时回收这么长时间运行的服务,导致在你的延迟逻辑中永远不会被调用!
Because Android is very likely to reclaim such a long running services when resources turn low, resultingin your delayed logic never being called!
从现在起 1 小时内激活回调的示例:
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
这篇关于如何在特定时间启动服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!