Android Alarm working, but delayed

狂风中的少年 提交于 2019-12-02 20:51:10

问题


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();
}

回答1:


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;



来源:https://stackoverflow.com/questions/20438405/android-alarm-working-but-delayed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!