我目前正在尝试编写警报管理器,该警报管理器将使警报每天在指定的时间段内发出。首先,我检查用户当天是否设置了警报:
if ((User.getReminderTime(Home.this) > 0)
&& (dt.getDate() != today.getDate() || dt.getDay() != today
.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);
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);
}
现在,我为此设置了一个测试环境,该环境每两分钟关闭一次,似乎工作正常,但是,当我部署到实际设备上时,接收方似乎没有收到警报。我认为这可能与设备处于睡眠状态有关,因此我添加了电源管理器。但是它仍然不起作用:
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();
任何人看到我在做的事情都是大错特错,还是我做错了?感谢您提供的所有帮助。
我通常按照以下方式做更多事情:
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);
这样,您不必担心在AlarmManager
中重新设置Service
。
我通常在应用启动时(在我的主要活动中为onResume
),并且在设置为接收BroadcastReceiver
的BOOT_COMPLETED
中运行这段代码。
我已经编写了有关创建Service
和使用AlarmManager
的指南,该指南基于我自己的经验以及我从观看Google I / O演讲中获得的一些技巧。如果您有兴趣,可以阅读here。
要在下面回答您的问题,我所能做的就是引用the docs:
。public void setInexactRepeating (int type, long triggerAtTime, long interval, PendingIntent operation)
安排重复的警报,其触发时间要求不正确;例如,闹钟每小时重复一次,但不一定每小时重复一次。这些警报比setRepeating(int,long,long,PendingIntent)所提供的严格重复执行具有更高的能效,因为系统可以调整警报的相位以使其同时触发,从而避免了使设备从睡眠中唤醒超过必要的时间。 >
您的警报的第一个触发器不会在请求的时间之前,但是在该时间之后几乎整个时间间隔内都不会发生。另外,虽然重复警报的整个时间段将按要求进行,但连续两次发出警报之间的时间可能会有所不同。如果您的应用要求非常低的抖动,请改用setRepeating(int,long,long,PendingIntent)。
总之,还不是很清楚。文档只说警报“可能有所不同”。但是,对于您而言,重要的是要知道第一个触发器在该时间之后几乎整个时间间隔内都不会发生
这正在工作,每5秒会发出警报