Search code examples
androidalarmmanager

how to set an Ending Point for Alarm Manager


I have an Alarm Manager that runs periodically , but I want to have a specific set of time that it will be running. For Example , lets say that we have a periodic Alarm Manager that is registered with a broadcast receiver and an Action is being performed every 30 minutes. The thing is that I want the Alarm Manager to be active for a specific time lets say 3 hours, so the Alarm manager should goes off 3 hours / 30 minutes or 6 times.

Code to start the define the Alarm Manager:

TimerPeriodic = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(getActivity(),AlarmReceiver.class);
    intent.putExtra(Constants.ALARM_ID, Constants.TIMER_PERIODIC_ID);
    TimerPeriodicPendingIntent = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);

Fire Alarm Manager:

long start = TimeUnit.MINUTES.toMillis(StartMinutes);
TimerPeriodic.setRepeating(
                            AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + start, start, TimerPeriodicPendingIntent);

Also the alarm Manager should be active if the Application is killed.

Thank you for any help!


Solution

  • It can be acheived by using Sqlite Db. where you store the Alaram ID,count,and repeation (How many time you want to repeat).

    when Alarm is trigger (AlarmReceiver.onReceive()) increment the count check with the condition with repeation. if it exceed just cancel it. Hope It will help :)

        @Override
        public void onReceive(Context context, Intent intent) {
          AlarmManager alarmManager = (AlarmManager) context.getApplicationContext().getSystemService(
                        context.ALARM_SERVICE);
        Intent myIntent = new Intent(context, AlarmReceiver.class);
        cancelAlarm(reminder.getId(),myIntent,alarmManager);
          }
    
        private void cancelAlarm(int notiId,Intent myIntent,AlarmManager alarmManager) {
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, notiId, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.cancel(pendingIntent);
         }