如何设置 Recurring AlarmManager 每天执行代码 [英] How to Set Recurring AlarmManager to execute code daily

查看:25
本文介绍了如何设置 Recurring AlarmManager 每天执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试编写警报管理器,每天在指定的时间段内发出警报.首先,我检查用户是否为那天设置了闹钟:

 if ((User.getReminderTime(Home.this) > 0)&&(dt.getDate() != today.getDate() || dt.getDay() != 今天.getDay())) {AppointmentManager.setFutureAppointmentCheck(this.getApplicationContext());User.setLongSetting(this, "futureappts", today.getTime());}

然后我将实际闹钟设置为在第二天的 12 点到 12 点 10 分之间响起:

 public static void setFutureAppointmentCheck(Context con) {AlarmManager am = (AlarmManager) con.getSystemService(Context.ALARM_SERVICE);日期 futureDate = new Date(new Date().getTime() + 86400000);随机生成器 = new Random();futureDate.setHours(0);futureDate.setMinutes(generator.nextInt(10));futureDate.setSeconds(0);意图意图=新意图(con,FutureAppointmentReciever.class);PendingIntent 发送者 = PendingIntent.getBroadcast(con, 0, intent,PendingIntent.FLAG_ONE_SHOT);am.set(AlarmManager.RTC_WAKEUP, futureDate.getTime(), sender);}

现在我为此设置了一个测试环境,每两分钟启动一次,它似乎工作正常,但是当我部署到实际设备时,接收器似乎没有收到警报.我认为这可能是设备休眠的问题,所以我添加了电源管理器.但是还是不行:

 PowerManager pm = (PowerManager) 上下文.getSystemService(Context.POWER_SERVICE);PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "keepAlive");wl.acquire();setFutureAppointments(context.getApplicationContext());AppointmentManager.setFutureAppointmentCheck(上下文.getApplicationContext());User.setLongSetting(context.getApplicationContext(), "futureappts",新日期().getTime());wl.release();

有人看到我做的明显错误还是我做错了?感谢您的任何帮助.

解决方案

我通常会做更多的事情:

Intent i = new Intent(this, MyService.class);PendingIntent pi = PendingIntent.getService(this, 0, i, 0);AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);上午.取消(pi);//取消任何现有的警报am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY,AlarmManager.INTERVAL_DAY, pi);

这样,您就不必担心在您的 Service 中重新设置 AlarmManager.

我通常在我的应用程序启动时(在我的主要活动中为onResume)和设置为接收BOOT_COMPLETED<的BroadcastReceiver运行这段代码/代码>.

我写了一份关于创建 Service 和使用 AlarmManager 的指南,它是基于我自己的经验和一些提示 &我从观看 Google I/O 演讲中学到的技巧.如果您有兴趣,可以在此处阅读.

<小时>

要在下面回答您的问题,我所能做的就是引用 文档:

<块引用>

public void setInexactRepeating(int类型,long triggerAtTime,long interval,PendingIntent操作)

安排一个触发时间要求不准确的重复警报;例如,每小时重复一次的闹钟,但不一定在每个小时的顶部.这些警报比 setRepeating(int, long, long, PendingIntent) 提供的严格重复更节能,因为系统可以调整警报的相位以使其同时触发,避免不必要地将设备从睡眠中唤醒.

您的闹钟的第一次触发不会在请求的时间之前,但在该时间之后的几乎整个时间间隔内都不会发生.此外,虽然重复警报的整个周期将按照要求进行,但警报的任何两次连续触发之间的时间可能会有所不同.如果您的应用程序需要非常低的抖动,请改用 setRepeating(int, long, long, PendingIntent).

总之,不是很清楚.文档只说警报可能会有所不同".但是,重要的是要知道第一个触发在那之后的几乎整个时间间隔内都不会发生.

I am currently trying to write alarm manager that will make an alarm go off within a specified period of time, daily. First I check to see if the user has had an alarm set for that for that day:

      if ((User.getReminderTime(Home.this) > 0)
    && (dt.getDate() != today.getDate() || dt.getDay() != today
      .getDay())) {
   AppointmentManager.setFutureAppointmentCheck(this
     .getApplicationContext());
   User.setLongSetting(this, "futureappts", today.getTime());
  }

Then I go and set the actual alarm to go off between 12 and 12:10 of the next day:

     public static void setFutureAppointmentCheck(Context con) {
  AlarmManager am = (AlarmManager) con
    .getSystemService(Context.ALARM_SERVICE);

  Date futureDate = new Date(new Date().getTime() + 86400000);
  Random generator = new Random();

  futureDate.setHours(0);
  futureDate.setMinutes(generator.nextInt(10));
  futureDate.setSeconds(0);

  Intent intent = new Intent(con, FutureAppointmentReciever.class);

  PendingIntent sender = PendingIntent.getBroadcast(con, 0, intent,
    PendingIntent.FLAG_ONE_SHOT);

  am.set(AlarmManager.RTC_WAKEUP, futureDate.getTime(), sender);

 }

Now I setup a test environment for this to go off every two minutes and it seems to be working fine, however when I deploy to an actual device, the reciever does not seem to be recieving the alarms. I thought it might be an issue with the device being asleep, so I added the power manager. But it still does not work:

      PowerManager pm = (PowerManager) context
    .getSystemService(Context.POWER_SERVICE);
  PowerManager.WakeLock wl = pm.newWakeLock(
    PowerManager.PARTIAL_WAKE_LOCK, "keepAlive");
  wl.acquire();
  setFutureAppointments(context.getApplicationContext());
  AppointmentManager.setFutureAppointmentCheck(context
    .getApplicationContext());
  User.setLongSetting(context.getApplicationContext(), "futureappts",
    new Date().getTime());
  wl.release();

Anyone see anything I am doing blatantly wrong or am I going about this incorrectly? thanks for any and all help.

解决方案

I usually do something more along the lines of:

Intent i = new Intent(this, MyService.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(pi); // cancel any existing alarms
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
    SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY,
    AlarmManager.INTERVAL_DAY, pi);

This way, you don't have to worry about re-setting the AlarmManager in your Service.

I usually run this bit of code when my app starts (onResume in my main activity) and in a BroadcastReceiver that is set up to receive BOOT_COMPLETED.

I've written a guide on creating Services and using the AlarmManager, which is based on my own experience and a few tips & tricks I picked off from watching a Google I/O talk. If you're interested, you can read it here.


To answer your question below, all I can do is quote the docs:

public void setInexactRepeating (int type, long triggerAtTime, long interval, PendingIntent operation)

Schedule a repeating alarm that has inexact trigger time requirements; for example, an alarm that repeats every hour, but not necessarily at the top of every hour. These alarms are more power-efficient than the strict recurrences supplied by setRepeating(int, long, long, PendingIntent), since the system can adjust alarms' phase to cause them to fire simultaneously, avoiding waking the device from sleep more than necessary.

Your alarm's first trigger will not be before the requested time, but it might not occur for almost a full interval after that time. In addition, while the overall period of the repeating alarm will be as requested, the time between any two successive firings of the alarm may vary. If your application demands very low jitter, use setRepeating(int, long, long, PendingIntent) instead.

In conclusion, it's not very clear. The docs only say that the alarm "may vary". However, it should be important for you to know that the first trigger might not occur for almost a full interval after that time.

这篇关于如何设置 Recurring AlarmManager 每天执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆