我需要定期检查数据更新,但数据只在白天更新,所以我希望这个重复 Action 只在那个时间段运行,以节省电池和带宽。
我该怎么办?
最佳答案
如果服务通过 HTTP get/post/whatever 请求与云通信,请注意 C2DM解决方案将延长电池生命周期,并且 SyncAdapter解决方案可以提供一些好处。 (我建议观看有关这两个主题的 Google I/O 视频。)
以下代码的功能与您最初询问的内容接近。
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:如何每 15 分钟使用 AlarmManager 重复一次服务,但只在上午 8:00 到晚上 18:00 运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6012563/