Search code examples
androidnotificationsalarmmanagerdate-format

Local Notification not firing if the phones time format is 12 hours


Im creating an application which fires a local notification when the time of the day is 2:00pm, I got it working fine when the Date/Time format of my device is set as 24Hours (which returns 14:00). But not when the device Date/Time format is 12Hours. Have i missed something? Here's my code below :

public class LocalNotificationsService extends Service {


    final static int RQS_1 = 1;
    static AlarmManager alarmManager;
    static PendingIntent pendingIntent;
    static Calendar calNow;
    static Calendar calSet;

    static Context context;
    @Override
    public void onCreate() {
        context = this;
        alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

            if(DateFormat.is24HourFormat(context)){
                setAlarm(14, 0);
            }else{
                setAlarm(2, 0);
            }

    }

    public static void setAlarm(int h, int m) {
        calNow = Calendar.getInstance();
        calSet = (Calendar) calNow.clone();

        calSet.set(Calendar.HOUR_OF_DAY, h);
        calSet.set(Calendar.MINUTE, m);
        calSet.set(Calendar.SECOND, 0);
        calSet.set(Calendar.MILLISECOND, 0);

        if (calSet.compareTo(calNow) <= 0) {
            // Today Set time passed, count to tomorrow
            calSet.add(Calendar.DATE, 1);
        }

        Intent intent = new Intent(context, LocalNotificationsReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(context, RQS_1, intent, 0);
        alarmManager.set(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), pendingIntent);

    }

}

Solution

  • Its obvious that you wont get notify if time format is changed to 12 hours.

    The Problem is with your setAlarm method. You are setting calSet's hour to Calendar.HOUR_OF_DAY.

    Incase of 12 houre, it has to be Calendar.HOUR.

    So please before settting that parameter,check time format of system and set accordingly.

    You can ask if you have any further queries :)