Android:如何每隔15分钟使用AlarmManager重复一次服务,但只能在上午8:00到下午18:00之间运行?

vir*_*sir 16 service android alarm

我需要定期检查数据更新,但数据只在白天更新,所以我希望这个重复操作仅在该时间段运行,以节省电池和带宽.

我该怎么办?

Pro*_*uce 29

如果服务通过HTTP get/post /任何请求与云通信,那么请注意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);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 人们为了一个目的创建了setRepeating.找到它.然后使用它.从技术上讲,这个例子也有效. (2认同)