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

Android app daily notification using Timer

我找到了使用 Timer 和 TimerTask 安排通知的教程,我正尝试在我的项目中实现它以在每天的特定时间发送通知。但是,如果指定的时间还没有过去并且第二天没有出现,它只会在当天触发通知。

这些是我的通知服务中使用的计时器方法class:

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() 方法中调用通知服务 class 使用:

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

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

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

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

此外,请记住,startService 将不再适用于 Android 11 月 1 日推出的 8 部手机。我建议改用 WorkManager。

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

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

我在我的项目中参考了 this link :