警报管理器在时间之前触发

时间:2013-07-16 14:29:50

标签: android alarmmanager android-alarms repeatingalarm

我正在尝试在我的应用程序中实现调度,该调度每天在设置的时间运行.scheduler在接下来的几个小时内运行良好但是如果我将其设置为时间过去并将其设置为启动调度程序立即运行。这是代码我甚至已经添加了代码以增加毫秒数,以防时间已经过去但仍无效。

    OnTimeSetListener onTimeSetListener  = new OnTimeSetListener(){
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            int timeDifference = 0;
            int splithour = 0;
            int splitmin = 0;
            String[] splitsecond = null;
                Calendar calNow = Calendar.getInstance();
                SimpleDateFormat simpDate;
                simpDate = new SimpleDateFormat("kk:mm:ss");


                calNow.set(Calendar.HOUR_OF_DAY, hourOfDay);
                calNow.set(Calendar.MINUTE, minute);
                calNow.set(Calendar.SECOND, 00);
                calNow.set(Calendar.MILLISECOND, 00);
                etTime.setText(simpDate.format(calNow.getTime()));

                String[] splitstrtime = simpDate.format(calNow.getTime()).split(":");

                splithour = Integer.parseInt(splitstrtime[0]);
                splitmin = Integer.parseInt(splitstrtime[1]);
                splitsecond = splitstrtime[2].split(" ");

                if (splitsecond[1].equalsIgnoreCase("pm")) {
                    timeDifference = 12;
                    if (splitsecond[1].equalsIgnoreCase("pm")
                            && splithour == 12) {
                        timeDifference = 0;
                        splithour = 12;

                    }
                } else if (splitsecond[1].equalsIgnoreCase("am")) {
                    timeDifference = 0;
                    if (splitsecond[1].equalsIgnoreCase("am")
                            && splithour == 12) {
                        timeDifference = 0;
                        splithour = 0;
                    }
                }
                splithour = timeDifference + Integer.parseInt(splitstrtime[0]);
                calNow.set(Calendar.HOUR_OF_DAY, splithour);
                System.out.println(splithour);
                calNow.set(Calendar.MINUTE, splitmin);
                System.out.println(splitmin);
                calNow.set(Calendar.SECOND,Integer.valueOf(splitsecond[0]));
                etTime.setText(simpDate.format(calNow.getTime()));

                Seconds=calNow.getTimeInMillis();
                System.out.println("Current"+Seconds);
                if(Seconds< System.currentTimeMillis())
                {
                    Seconds=Seconds+1*24*60*60;
                    System.out.println("Alter"+Seconds);
                }
        }};

1 个答案:

答案 0 :(得分:1)

您的方法是正确的,如果您希望明天触发警报已经过了一段时间,您需要为您的时间添加一天。你做了一个错误,并且你应该在几毫秒内添加秒。请注意,您的变量Seconds包含毫秒:

Seconds=calNow.getTimeInMillis();

但是你要加秒而不是毫秒:

Seconds=Seconds+1*24*60*60;

试试这样:

Seconds=Seconds+1*24*60*60*1000;