-2

i want to trigger alarm on hourly basis like from 6am to 6pm and it also trigger every day from 6 am to 6 pm. do i require mutltiple alarms ? help needed

Intent intent1 = new Intent(context, cls);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC_WAKEUP,setcalendar.getTimeInMillis(), AlarmManager.INTERVAL_HOUR, pendingIntent);
  //  
    Toast.makeText(context, "Notification Alarm set", Toast.LENGTH_SHORT).show();

The above alarm is only triggered on hourly basis only for one day ,but i want it to be triggered on hourly basis on every day

vnibin
  • 1
  • 1

1 Answers1

0

If it will be always repeated between 6AM and 6PM daily you don't need database then. Also be sure that you schedule an alarm to IntentService or BroadcastReceiver in your PendingIntent. In onReceive get current hour, check if it is between 6AM and 6PM, if is, fire alarm. If not, cancel current alarm (battery saving), schedule next alarm for 6AM. Meanwhile write an algorithm that checks current day. Details I left in TODOs in the sample code.

    Calendar calendar = Calendar.getInstance();
    int hour = calendar.get(Calendar.HOUR_OF_DAY);
    if (hour >= 6 && hour <= 18){
        //fire alarm
    } else if (hour > 19 || hour < 6) {
        Intent intent1 = new Intent(context, cls);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_CANCEL_CURRENT);
        pendingIntent.cancel();
        calendar.set(Calendar.HOUR_OF_DAY, 6);
        //TODO: Write an algorithm that checks if current day + 1 will be still in the same month,
        //TODO: what I mean if it is out of range of month, e.g 30th of Febraury, then get current month and add 1
        //TODO: If there is currently 31st December, change day to be equal of 1, get current year, add 1 etc.
        int currentday = calendar.get(Calendar.DAY_OF_MONTH);
        calendar.set(Calendar.DAY_OF_MONTH, currentday + 1);
        Intent intent1 = new Intent(context, cls);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP,setcalendar.getTimeInMillis(), AlarmManager.INTERVAL_HOUR, pendingIntent);
    }
Domin
  • 1,075
  • 1
  • 11
  • 28