TL; DR - AlarmManager .setRepeating立即启动而不是所需的未来时间..(例如从现在起5分钟)
所以基本上我正在启动一个报警管理器,我给它留下了操作的时间,并且由于某种原因它立即启动..用户正在从时间选择器中选择一个时间,我设置了这个时间为下一个警报。 代码如下:
- 这个方法得到报警前的剩余时间,这被用作alarmManager的triggerInMillis。
/** calculate the time left until the alarm with calendar */
private static long getTimeFromCalendar(final int hourOfDay, final int minute) {
Date dat = new Date();//initializes to now
Calendar cal_alarm = Calendar.getInstance();
Calendar cal_now = Calendar.getInstance();
cal_now.setTime(dat);
cal_alarm.setTime(dat);
cal_alarm.set(Calendar.HOUR_OF_DAY,hourOfDay);
cal_alarm.set(Calendar.MINUTE, minute);
cal_alarm.set(Calendar.SECOND,0);
if(cal_alarm.before(cal_now)){
cal_alarm.add(Calendar.DATE,1);
}
long calAlarm = cal_alarm.getTimeInMillis();
long calNow = cal_now.getTimeInMillis();
long timeLeft = (calAlarm - calNow);
return timeLeft;
}
然后我调用-startAlarm-方法:
private static void startAlarm(final Enums typeToStart) {
final PendingIntent pendingIntent = GBAlarms.createPendingIntent(OnAlarmReceiver.class, Constants.typeEnum, typeToStart);
final long timeToAlarm = Utils.getTimeToAlarm(typeToStart);
long repeatTime = Constants._24hours;
GBAlarms.createRepeatingAlarm(timeToAlarm, repeatTime, pendingIntent);
}
最后,我的-GBAlarms.class-我创建了我的警报和待处理的意图。
public class GBAlarms {
/** Define our AlarmManager */
private static AlarmManager mgr = (AlarmManager) BaseApplication.getAppContext().getSystemService(Context.ALARM_SERVICE);
/** Create a new PendingIntent */
public static PendingIntent createPendingIntent(final Class destination, @Nullable final String extra, Enums.TeaType type) {
Intent i = new Intent(BaseApplication.getAppContext(), destination);
if (extra != null && type != null) { i.putExtra(extra, type); }
PendingIntent pi = PendingIntent.getBroadcast(BaseApplication.getAppContext(), type.getValue() , i, 0);
return pi;
}
/** Create a new repeating Alarm */
public static void createRepeatingAlarm(final long time, final long repeatTime, final PendingIntent pi) {
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, time, repeatTime, pi);
}
}
我不明白,出于某种原因,当我在-createRepeatingAlarm-方法中设置闹钟时,闹钟弹出正确,我当然调试了,时间参数看起来合法......如果我将它设置为3分钟, 10分钟,它将时间留在触发器中..
任何人都可以发现我的错误吗?也许我错过了什么?
非常感谢你的帮助。
答案 0 :(得分:0)
您正在创建“待处理”闹钟, 在特定间隔后重复的警报。
诀窍是在你开始的那一刻取消当前的闹钟。
请看下面的代码:你必须用方法调用getBroadcast方法
国旗public static long binaryToInteger(String binaryString) {
char[] chars = binaryString.toCharArray();
long resultInt = 0;
int placeHolder = 0;
for (int i=chars.length-1; i>=0; i--) {
if (chars[i]=='1') {
resultInt += Math.pow(2,placeHolder);
}
placeHolder++;
}
return resultInt;
}
PendingIntent.CANCEL_CURRENT