【问题标题】:Android: How to repeat a service with AlarmManager every 15 minutes, but only run from 8:00AM to 18:00PM?Android:如何每 15 分钟使用 AlarmManager 重复一次服务,但只在上午 8:00 到晚上 18:00 运行?
【发布时间】:2011-05-16 01:53:26
【问题描述】:

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

我该怎么办?

【问题讨论】:

    标签: android service alarm


    【解决方案1】:

    如果服务通过 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);
      }
    }

    【讨论】:

    • 我认为这只是运行一次,您可能想使用 alarmManager.setRepeating 每隔 15 分钟运行一次,如果我错了,请纠正我。
    • 不,它不仅在安排警报时执行一次。当触发此警报时(15 分钟后),服务会再次运行,以此类推。
    • 你为什么要这样做而不是使用 setRepeating?这似乎不太可靠,并且需要更多的工作。
    • 人们出于某种目的创建了 setRepeating。找到它。然后使用它。从技术上讲,这个例子也很有效。
    • 如果您使用 Joda 时间 (joda.org/joda-time),则可以在此代码中高度简化时间计算。例如,将 15 分钟添加到当前时间的 3 行可以这样重写:DateTime nextUpdateTime = DateTime.now().plusMinutes(15);
    【解决方案2】:

    按照这些简单的步骤,让 servce 在 android 设备中永远存在。 1. 每 15 分钟使用警报管理器调用一次服务。 2. 在 onStart 方法中返回 START_STICKY。 3.在销毁时调用警报管理器并使用重新启动服务 启动服务方法。 4.(可选)在 onTaskRemoved 方法中重复第 3 点。

    【讨论】:

      猜你喜欢
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-03
      • 1970-01-01
      • 2016-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多