使用计时器的Android应用每日通知

时间:2018-09-26 08:11:23

标签: java android timer android-notifications timertask

我找到了一个使用Timer和TimerTask进行定时通知的教程,我试图在我的项目中实现它,以便每天在特定时间发送通知。但是,只有在指定的时间未过去且第二天没有显示时,才在当天触发通知。

这些是我的Notification Service类中使用的计时器方法:

public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer
        Calendar today = Calendar.getInstance();
        Calendar tomorrow = Calendar.getInstance();
        tomorrow.set(Calendar.HOUR_OF_DAY, 17);
        tomorrow.set(Calendar.MINUTE, 2);
        tomorrow.set(Calendar.SECOND, 0);
        if(today.compareTo(tomorrow) > 0)
            tomorrow.add(DATE, 1);
        long initialDelay = tomorrow.getTimeInMillis() - today.getTimeInMillis();
        timer.scheduleAtFixedRate(timerTask, initialDelay, 1000*60*60*24);
    }

public void initializeTimerTask() {

        timerTask = new TimerTask() {
            public void run() {

                //use a handler to run a toast that shows the current timestamp
                handler.post(new Runnable() {
                    public void run() {

                        sendNotification();

                    }
                });
            }
        };
    }

我正在使用以下方法在MainActivity.class的onStop()方法中调用Notification Service类:

startService(new Intent(this, NotificationService.class));

我不确定这是否是正确的调用位置,并且无法调试,并且在关闭应用程序后无法查看计时器是否在工作。

2 个答案:

答案 0 :(得分:0)

我建议您研究AlarmManager以实现此目的。您不必为此重新发明轮子。它允许您通过设置时间间隔来唤醒应用程序。

alarmMgr.setRepeating(
        AlarmManager.RTC_WAKEUP,
        calendar.timeInMillis,
        1000 * 60 * 20,
        alarmIntent
)

此外,请记住,11月1日起,startService将不再在Android 8手机上运行。我建议改为使用WorkManager。

答案 1 :(得分:0)

我在我的项目中使用了此代码,并且运行顺利:

   public void setAlarm() {

    Intent serviceIntent = new Intent(this, CheckRecentRun.class);
    PendingIntent pi = PendingIntent.getService(this, 131313, serviceIntent,
                                                PendingIntent.FLAG_CANCEL_CURRENT);

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delay, pi);
    Log.v(TAG, "Alarm set");        
}
public void sendNotification() {

    Intent mainIntent = new Intent(this, MainActivity.class);
    @SuppressWarnings("deprecation")
    Notification noti = new Notification.Builder(this)
        .setAutoCancel(true)
        .setContentIntent(PendingIntent.getActivity(this, 131314, mainIntent,
                          PendingIntent.FLAG_UPDATE_CURRENT))
        .setContentTitle("We Miss You!")
        .setContentText("Please play our game again soon.")
        .setDefaults(Notification.DEFAULT_ALL)
        .setSmallIcon(R.drawable.ic_launcher)
        .setTicker("We Miss You! Please come back and play our game again soon.")
        .setWhen(System.currentTimeMillis())
        .getNotification();

    NotificationManager notificationManager
        = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(131315, noti);

    Log.v(TAG, "Notification sent");        
}

我为我的项目做过引用的地方此链接

https://stackoverflow.com/a/22710380/7319704