【问题标题】:AlarmManager - How to set a Notification to appear annuallyAlarmManager - 如何设置每年显示的通知
【发布时间】:2015-04-30 17:53:15
【问题描述】:

我希望根据输入的日期(生日)每年显示一条通知。我有其他一切工作吧如何每年设置通知。正如您在下面看到的,我已将代码更改为在间隔所在的位置说“HERE”。有几天的间隔,我知道我可以将它乘以 365。但是如果它是闰年会发生什么......

int REQUEST_CODE = 7;
Intent intent = new Intent(Activity2.this, Receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Activity2.this, REQUEST_CODE, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(am.RTC_WAKEUP, System.currentTimeMillis(), HERE, pendingIntent);

【问题讨论】:

  • 请记住,每次重新启动设备时都需要重新创建警报,这一点几乎可以在一年后得到保证。所以你需要创建一个BroadcastReceiver 来监听ACTION_BOOT_COMPLETED 操作(并且你需要RECEIVE_BOOT_COMPLETED 权限),并在每次启动时重置警报。

标签: android notifications alarmmanager date


【解决方案1】:

您可以将“HERE”替换为确定从今天起的下一个 2 月是否为闰年的方法,然后根据这些检查返回值 365 或 366 天(请注意以毫秒的形式)。

private long millisUntilNextYear(){

    //Set days in a year for Leap and Regular
    final int daysInLeapYear = 366;
    final int daysInYear = 365;

    //Get calendar instance
    GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();

    //Get this year and next year
    int thisYear = cal.get(GregorianCalendar.YEAR);
    int nextYear = thisYear + 1;

    //Get today's month
    int thisMonth = cal.get(GregorianCalendar.MONTH);

    //Get today's date
    int dayOfMonth = cal.get(GregorianCalendar.DAY_OF_MONTH);

    //Is today before February? If so then the following February is in THIS year
    if (thisMonth < GregorianCalendar.FEBRUARY){

        //Check if THIS year is leapYear, and return correct days (converted to millis)
        return cal.isLeapYear(thisYear) ? daysToMillis(daysInLeapYear) : daysToMillis(daysInYear);
    }

    //Is today after February? If so then the following February is NEXT year
    else if (thisMonth > GregorianCalendar.FEBRUARY) {
        //Check if NEXT year is leapYear, and return correct days (converted to millis)
        return cal.isLeapYear(nextYear) ? daysToMillis(daysInLeapYear) : daysToMillis(daysInYear);
    }

    //Then today must be February.
    else {
        //Special case: today is February 29
        if (dayOfMonth == 29){
            return daysToMillis(daysInYear);
        } else {
            //Check if THIS year is leapYear, and return correct days (converted to millis)
            return cal.isLeapYear(thisYear) ? daysToMillis(daysInLeapYear) : daysToMillis(daysInYear);
        }
    }
}

【讨论】:

  • 我仍然无法弄清楚这一点,但我知道你的意思!你能进一步解释甚至给我一些示例代码吗? @user3829751
  • 为您的复制和粘贴乐趣编辑,添加了代码示例:)
【解决方案2】:

1) 以 MM/DD/YY 格式保存日期。

2) 在您打开应用时(或在不同时间)阅读这些日期

3) 为单日/今天设置警报。

此外,您还可以显示下周/下个月等的生日。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多