好的,根据我阅读的其他类似答案,我想我为我的问题找到了一个简单的解决方案。我只需要在每次应用程序启动时运行这些功能。我不需要使用任何后台服务,比如 WorkManager。我只需要在 SharedPreferences 中存储系统重置值的最后日期。然后,每次我打开应用程序时,它都会检查今天是否与上次重置日不同的一周。如果是真的,那么我在问题中运行“for 循环”,并在 SharedPreferences 中将最后一个重置日更新为今天。如果是假的,我什么都不做。
inSameCalendarWeek 方法检查这一天是否与今天的同一年在同一周(Locale.US 保证一周从星期日开始。但我可以将其更改为 Locale.getDefault() 以更灵活)。此外,例如,如果 12 月 31 日与 1 月 1 日在同一周,即使它们在不同年份,该方法也会返回 true。
private void checkAndResetDoneDays() {
long lastResetDay = settings.getLong(LAST_DAY_RESET, 0);
LocalDate date = Instant.ofEpochMilli(lastResetDay).atZone(ZoneId.systemDefault()).toLocalDate();
if (!inSameCalendarWeek(date)) {
resetDoneDays();
settings.edit()
.putLong(LAST_DAY_RESET, LocalDate.now(ZoneId.systemDefault()).atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli())
.commit();
}
}
public boolean inSameCalendarWeek(LocalDate firstDate) {
LocalDate secondDate = LocalDate.now(ZoneId.systemDefault());
// get a reference to the system of calendar weeks in US Locale (to guarantee that week starts on Sunday)
WeekFields weekFields = WeekFields.of(Locale.US);
// find out the calendar week for each of the dates
int firstDatesCalendarWeek = firstDate.get(weekFields.weekOfWeekBasedYear());
int secondDatesCalendarWeek = secondDate.get(weekFields.weekOfWeekBasedYear());
/*
* find out the week based year, too,
* two dates might be both in a calendar week number 1 for example,
* but in different years
*/
int firstWeekBasedYear = firstDate.get(weekFields.weekBasedYear());
int secondWeekBasedYear = secondDate.get(weekFields.weekBasedYear());
// return if they are equal or not
return firstDatesCalendarWeek == secondDatesCalendarWeek
&& firstWeekBasedYear == secondWeekBasedYear;
}