Search code examples
javaandroidalarmmanagerrepeatingalarm

is there a way wake up my android app daily at 12 to run a bit of code


is there a way wake up my android app daily at 12 to run a bit of code like in alarm receiver but exactly at 12 mine runs late like 10min to hours

   Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 12);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        if (Calendar.getInstance().after(calendar)) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 100, new Intent(context, MyReceiver.class), PendingIntent.FLAG_IMMUTABLE);
        AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        manager.cancel(pendingIntent);

        manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 86400000, pendingIntent);

it is sometime running fine mostly not


Solution

  • You are using setInexactRepeating() and from it’s name it says it is inexact so the system can delay the alarm in order to achieve exact behavior you will have to use setAlamClock() and each time it fires at 12 you will have to schedule another one for the next time since there is no exact repeating one also you need to consider things like if the device reboots(all alarms are going to be cancelled) so a receiver to reschedule them will do the job.