Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 830
Pentium10 Avatar asked Jun 07 '10 20:06

Pentium10


People also ask

What is an exact alarm?

What is this permission? The new exact alarm permission ( SCHEDULE_EXACT_ALARM ) was created to save system resources. Alarms that must be executed in an exact time may be triggered when the phone is on power-saving mode or Doze, making the app consumes more battery than it should.

What is alarm in Android?

The alarm is an Intent broadcast that goes to a broadcast receiver that you registered with Context. registerReceiver(BroadcastReceiver, IntentFilter) or through the <receiver> tag in an AndroidManifest. xml file. Alarm intents are delivered with a data extra of type int called Intent.


2 Answers

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).

like image 148
Mark B Avatar answered Oct 16 '22 17:10

Mark B


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 ...
    }
like image 34
Tom Avatar answered Oct 16 '22 17:10

Tom