I'm trying to make a simple alarm clock and everything is working as it should, but I'm finding that the firing of the alarm is delayed.

I think the problem may be that the system is recording the exact millisecond I am setting the alarm, and then firing the alarm at that exact millisecond. So for example, if I make an alarm for 8:00am but I set the alarm at 10:00:30.225pm, then the alarm will fire at 8:00:30.225am.

How would I go about making sure the alarm fires exactly on the minute? I tried using setExact(...) but that just caused my app to crash.

Thanks in advance!

public void setAlarm(View view) {

    TimePicker timePick = (TimePicker) findViewById(R.id.time_pick);
    Calendar calendar = Calendar.getInstance();

    //Set alarm based on values in time picker
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, timePick.getCurrentHour());
    calendar.set(Calendar.MINUTE, timePick.getCurrentMinute());

    setAlarmDisplay(calendar); //shows time in EEE, MMM d yyyy hh:mm aa format

    Intent intent = new Intent(this, AlarmReceiver.class);
    alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    alarmManager = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);

    Toast.makeText(view.getContext(), "Alarm set!", Toast.LENGTH_LONG).show();
}
有帮助吗?

解决方案

I'd rather comment this but I don't have 50 rep yet so I'll have to submit an answer.

I think the problem is the line

calendar.setTimeInMillis. 

You then set the hour and minute but everything else (seconds and ms) stay exactly as it was when you ran that code.

If you want the alarm to go off at exactly 10:30, set the hours, set the minutes and then reset the seconds and milliseconds to be 0;

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top