how to repeat alarm after 1 day in android

11,199

Solution 1

Hopefully below code will help, I used the same in my app. Here the argument passed in AlarmManager class for repeating should be 24*60*60*1000

AlarmManager am = (AlarmManager) ct.getSystemService(Context.ALARM_SERVICE);         
Intent intent1 = new Intent(ct, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ct, 0,intent1, PendingIntent.FLAG_CANCEL_CURRENT);

Date curr=new Date();
curr.setHours(h);
curr.setMinutes(m);
c.setTime(curr);
c.set(Calendar.SECOND, 0);

Calendar c1 = Calendar.getInstance();
am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),24*60*60*1000, pendingIntent);

Solution 2

It is better to use inexactrepeating instead of setExactRepeating keeping in mind of battery consumption as per android documentation.

      public void scheduleAlarms(AlarmManager mgr, PendingIntent pi, Context context) 
                {

                    // every day at scheduled time 
                    Calendar calendar = Calendar.getInstance();
                   // if it's after or equal 9 am schedule for next day
                   if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) >= 9) {
                        calendar.add(Calendar.DAY_OF_YEAR, 1); 
                    }
                    calendar.set(Calendar.HOUR_OF_DAY, 9);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);

              mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
    }
Share:
11,199
picaso
Author by

picaso

Updated on June 04, 2022

Comments

  • picaso
    picaso almost 2 years

    I m using the alarm manager in my app and i want to repeat alarm after one day. the alarm should be invoked after one day when invoked once by time.Please help. Thanks in advance.

    if(str_freqSchedule.equals(checkForDaily)){
                Calendar calendar = Calendar.getInstance();
                //calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR));
                calendar.set(Calendar.HOUR_OF_DAY, hr);
                calendar.set(Calendar.MINUTE, min);
                calendar.set(Calendar.SECOND,0);
    
                Intent intent = new Intent(this, AlarmReceiverActivity.class);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(
                        this.getApplicationContext(), j, intent, PendingIntent.FLAG_CANCEL_CURRENT);
                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),(24*60*60*1000),pendingIntent);
                j++;
    
            }