How to set an alarm to fire properly at fixed time?

我只是一个虾纸丫 提交于 2019-11-27 12:34:46

问题


I have this code

Calendar c = new GregorianCalendar();
        c.add(Calendar.DAY_OF_YEAR, 1);
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 22);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);

        // We want the alarm to go off 30 seconds from now.
        long firstTime = SystemClock.elapsedRealtime();
        firstTime += 30*1000;
        long a=c.getTimeInMillis();

        // Schedule the alarm!
        AlarmManager am = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                c.getTimeInMillis(), 1*60*60*1000, sender);

It is not executed at 23:22h

What I am doing wrong? I noticed firstTime and c.getTimeInMillis() differs a lot in size and length. When I use firstTime, so when set to 30 seconds, the alarm is executed well.


回答1:


You are using the AlarmManager.ELAPSED_REALTIME_WAKEUP flag, but you are using a Calendar object. These two things don't go together.

You need to use AlarmManager.RTC or AlarmManager.RTC_WAKEUP if you are specifying the alarm time using a Calendar or Date object (milliseconds since 1970).

You use AlarmManager.ELAPSED_REALTIME or AlarmManager.ELAPSED_REALTIME_WAKEUP when you are specifying the alarm time via SystemClock.elapsedRealtime() (milliseconds since the phone booted).




回答2:


I had success with the following code, if you only want to set the alarm for the next occurance of hh:mm

Calendar cal = new GregorianCalendar();
    cal.setTimeInMillis(System.currentTimeMillis());
    cal.set(Calendar.HOUR_OF_DAY, 22);
    cal.set(Calendar.MINUTE, 19);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    //check if we want to wake up tomorrow
    if (System.currentTimeMillis() > cal.getTimeInMillis()){
        cal.setTimeInMillis(cal.getTimeInMillis()+ 24*60*60*1000);// Okay, then tomorrow ...
    }



回答3:


To get the alarm to go off 30 seconds from now, use

Calendar cal = Calendar.getInstance();

to get the current time, and then

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+30000, sender); 

Edit:

I think the problem is the ELAPSED_REALTIME_WAKEUP. This tells the AlarmManager that the time you are giving it is based on time since system startup. This is fine for 30 seconds from now, but if you want it to be based on real time you should use RTC, or RTC_WAKEUP. See javadoc for full explanation of those types.



来源:https://stackoverflow.com/questions/2992882/how-to-set-an-alarm-to-fire-properly-at-fixed-time

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