Seng Seng - 16 days ago 6
Android Question

AlarmManager not trigger current time

I making an android alarm app and setting alarm by using code below:

Calendar alarm = Calendar.getInstance();
alarm.set(Calendar.YEAR, year1);
alarm.set(Calendar.MONTH, month1);
alarm.set(Calendar.DAY_OF_MONTH, day1);
alarm.set(Calendar.HOUR_OF_DAY, hour1);
alarm.set(Calendar.MINUTE, min1);
alarm.set(Calendar.SECOND, 0);

if(alarm.before(Calendar.getInstance()))
{
alarm.add(Calendar.DATE, 1);
Toast.makeText(getActivity(),"You selected the past time",Toast.LENGTH_SHORT).show();
}
else
{
Intent myIntent = new Intent(getActivity(), MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(getActivity().ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, alarm.getTimeInMillis(), pendingIntent);
}


Everything works fine, but the problem is when I select the current date,month,year and also the current time, it will display "you selected the past time". How to solve this problem?

Answer

Try this. Hope that it will solve your problem.

Calendar alarm = Calendar.getInstance();
Calendar copy = (Calendar) alarm.clone();

alarm.set(Calendar.YEAR, year1);
alarm.set(Calendar.MONTH, month1);
alarm.set(Calendar.DAY_OF_MONTH, day1);
alarm.set(Calendar.HOUR_OF_DAY, hour1);
alarm.set(Calendar.MINUTE, min1);

int result = alarm.compareTo(copy);

if (result == 0) 
{
    Toast.makeText(getActivity(), "You selected current time", Toast.LENGTH_SHORT).show();
}
else if (result < 0)
{
    alarm.add(Calendar.DATE, 1);
    Toast.makeText(getActivity(), "You selected the past time", Toast.LENGTH_SHORT).show();
}
else
{        
    Intent myIntent = new Intent(getActivity(), MyReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent, 0);
    AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(getActivity().ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC, alarm.getTimeInMillis(), pendingIntent);
}