0

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

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

1 回答 1

1

您的方法是正确的,如果时间已经过去,您需要在时间上增加一天,因为您希望明天触发警报。但是,您犯了一个错误,那就是您在应该是毫秒的情况下添加了秒。请注意,您的变量 Seconds 包含毫秒:

Seconds=calNow.getTimeInMillis();

但是您添加的是秒而不是毫秒:

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

试试这样:

Seconds=Seconds+1*24*60*60*1000;
于 2013-07-16T14:57:51.573 回答