gpt4 book ai didi

android - 为一周中的特定日子重复闹钟android

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:30:12 25 4
gpt4 key购买 nike

在我的应用程序中,我有一个功能可以在 4 个 senerios 中触发警报:

  • 仅限用户选择的日期和时间一次
  • 每天在选定的时间
  • 每周根据选择的日期和时间
  • 用户选择的自定义星期几

我使用以下方法成功实现了前 3 个 senerios:

只有一次:

Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.YEAR, Integer.parseInt(date[0]));
calendar.set(Calendar.MONTH, (Integer.parseInt(date[1])) - 1);
calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(date[2]));
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(time[1]));
calendar.set(Calendar.SECOND, 0);

alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

每日安排:

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(time[1]));
calendar.set(Calendar.SECOND, 0);

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

对于每周安排(根据系统日期):

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());

calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(time[1]));
calendar.set(Calendar.SECOND, 0);
//long interval = calendar.getTimeInMillis() + 604800000L;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, pendingIntent);

对于用户选择的自定义工作日(例如,仅周一和周五,每周重复一次),我使用的代码与我用于按迭代进行每周调度的代码相同。但是它不在星期一工作(在星期五之前设置)并且在星期五工作。此外,如果今天(系统日期)是星期一或星期五,它不会触发今天的警报。

那么我如何为一周中的自定义日期实现每周警报计划?

最佳答案

您无法告诉警报管理器您希望它在哪几天触发。

一个解决方案是为一周中的每一天设置一个闹钟,您希望它每周触发一次。

因此对于周一和周五的场景,您可以在周一设置每周重复提醒,在周五设置每周重复提醒。

示例代码:

private void scheduleAlarm(int dayOfWeek) {

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);

// Check we aren't setting it in the past which would trigger it to fire instantly
if(calendar.getTimeInMillis() < System.currentTimeMillis()) {
calendar.add(Calendar.DAY_OF_YEAR, 7);
}

// Set this to whatever you were planning to do at the given time
PendingIntent yourIntent;

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, yourIntent);
}

private void setUpAlarms() {

scheduleAlarm(Calendar.MONDAY);
scheduleAlarm(Calendar.FRIDAY);
}

关于android - 为一周中的特定日子重复闹钟android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36550991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com