简体   繁体   中英

Why does my yearly alarm not work properly?

i'm trying to set alarm for yearly events with this code

MyAlarmReceiver.java

mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
              
Intent intent1 = new Intent(context, AlarmReceiver.class);
intent1.putExtra(ReminderEditActivity.EXTRA_REMINDER_ID, Integer.toString(mReceivedID));
mPendingIntent = PendingIntent.getBroadcast(context, mReceivedID, intent1, PendingIntent.FLAG_CANCEL_CURRENT);

Calendar calendar = Calendar.getInstance();
GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();

if(cal.isLeapYear(calendar.get(Calendar.YEAR))) {
    mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
         calendar.getTimeInMillis() + (86400000L*366), mPendingIntent);
} else {
    mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
         calendar.getTimeInMillis() + (86400000L*365), mPendingIntent);}
}

But it only works with 365 days even the year is definitely a leap year?

The java.util.GregorianCalendar.isLeapYear() method determines if the given year passed as a parameter to the function is a leap year or not and returns true if the given year is a leap year and false otherwise.

Syntax:

public boolean isLeapYear(int year)

Parameters: This function accepts a single integer parameter year that represents the year which the function needs to check for whether it is a leap year or not.

Return Values: The function returns a boolean value. If the year passed as a parameter is a leap year, it returns true and false otherwise.

Example:

import java.io.*;
import java.util.*;
  
class GFG {
     public static void main(String[] args) {
      
      // Create a new calendar
      GregorianCalendar c = (GregorianCalendar) GregorianCalendar.getInstance();
  
      // Display the current date and time
      System.out.println("Current Date and Time : " + c.getTime());
  
      int year = c.get(GregorianCalendar.YEAR);
      if(c.isLeapYear(year)) {
           System.out.println(year + " is leap year");
      } else {
          System.out.println(year + " is Not a leap year");
      }
   }
}

Reference : isLeapYear

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM