Android: How to repeat a service with AlarmManager every 15 minutes, but only run from 8:00AM to 18:00PM?

限于喜欢 提交于 2019-11-27 00:24:10

问题


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.

What should I do?


回答1:


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.)

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);
  }
}



回答2:


Follow these easy steps to keep servce alive forever in android device. 1. Call a service by using alarm manager for every 15 minutes. 2. return START_STICKY in onStart method. 3. In on destroy call the alarm manager and restart service by using startService method. 4.(Optional)Repeat the point number 3 in onTaskRemoved method.



来源:https://stackoverflow.com/questions/6012563/android-how-to-repeat-a-service-with-alarmmanager-every-15-minutes-but-only-ru

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!