Android的:如何与AlarmManager重复服务,每15分钟一班,但只从上午8:00运行至18:00 PM? [英] Android: How to repeat a service with AlarmManager every 15 minutes, but only run from 8:00AM to 18:00PM?
问题描述
我需要periodly检查数据更新,但数据只在白天更新,所以我只想在这时间段重复这个动作奔跑为节省电池和带宽。
I need to check data update periodly, but the data is only updating during the daytime, so I want this repeating action run only in that time section for saving battery and bandwidth.
我应该怎么办?
推荐答案
如果该服务被谈论到云与HTTP GET / POST /任何请求,然后记下一个的C2DM 解决方案将净赚更好的电池寿命,以及一个的 SyncAdapter 解决方案可以提供一些好处。 (我建议看谷歌I / O上的视频这两个主题。)
If the service is talking to the cloud with HTTP get/post/whatever requests, then note that a C2DM solution would net better battery life, and that a SyncAdapter solution could provide a few benefits. (I recommend watching the Google I/O videos on both topics.)
下面code做一些接近您最初问什么。
The following code does something close to what you originally asked about.
public class MyUpdateService extends IntentService
{
public MyUpdateService()
{
super(MyUpdateService.class.getSimpleName());
}
@Override
protected void onHandleIntent(Intent intent)
{
// Do useful things.
// After doing useful things...
scheduleNextUpdate();
}
private void scheduleNextUpdate()
{
Intent intent = new Intent(this, this.getClass());
PendingIntent pendingIntent =
PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// The update frequency should often be user configurable. This is not.
long currentTimeMillis = System.currentTimeMillis();
long nextUpdateTimeMillis = currentTimeMillis + 15 * DateUtils.MINUTE_IN_MILLIS;
Time nextUpdateTime = new Time();
nextUpdateTime.set(nextUpdateTimeMillis);
if (nextUpdateTime.hour < 8 || nextUpdateTime.hour >= 18)
{
nextUpdateTime.hour = 8;
nextUpdateTime.minute = 0;
nextUpdateTime.second = 0;
nextUpdateTimeMillis = nextUpdateTime.toMillis(false) + DateUtils.DAY_IN_MILLIS;
}
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, nextUpdateTimeMillis, pendingIntent);
}
}
这篇关于Android的:如何与AlarmManager重复服务,每15分钟一班,但只从上午8:00运行至18:00 PM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!