计时器不运行

时间:2014-06-04 20:28:39

标签: android timer timertask

我正在设置今天的计时器(日期是:2014年4月6日,如果重要,小时是23:25),但是timerTask没有运行..

我的代码如下:

private void makeARemainder() {
                TimerTask timerTask = new RemindAboutEvent();
                // running timer task as daemon thread
                Timer timer = new Timer(true);
                int day = dayOfMonth;
                @SuppressWarnings("deprecation")
                Date when = new Date(2014, Calendar.JUNE, 4);
                timer.schedule(timerTask, when);

            }


class RemindAboutEvent extends TimerTask {
            @Override
            public void run() {
                String title = "Event is comming!";
                String messageBody = info.eventName;
                showNotification(title, messageBody);
            }
        }

我试着查看之前的帖子,但无法弄清楚出了什么问题。

编辑: 我想要注意,活动在makeARemainder方法之后完成,并且应用程序仍在工作,但是正在运行不同的活动。

有人可以告诉timerTask不运行的原因吗? 非常感谢!

2 个答案:

答案 0 :(得分:0)

您的Date已成为过去。确保您的日期是将来:

// Using this contructor: Date(int year, int month, int day, int hour, int minute, int second)
Date when  = new Date(2014, 6, 4, 13, 45, 00); // This time is in the future for me
// or
Date nowPlus30 = new Date();
timer.schedule(timerTask, now.getTime() + 30 * 1000);

答案 1 :(得分:0)

我通过以下代码解决了这个问题:

private void makeARemainder() {
                TimerTask timerTask = new RemindAboutEvent();
                Timer timer = new Timer(true);
                String when = info.eventDayOfMonth + "/" + info.eventMonth
                        + "/" + info.eventYear + " " + info.eventHour + ":"
                        + info.eventMinute;
                try {
                    timer.schedule(timerTask,
                            (new SimpleDateFormat("dd/MM/yyyy HH:mm")
                                    .parse(when/* "8/6/2014 20:28" */)));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }