Question

I want to trigger repeating alarm at specific time & I'm using below code but it does not trigger the alarm at the time I wanted.

  boolean weeklyAlarmUp = (PendingIntent.getBroadcast(ctxt, 0, new Intent(ctxt, ScheduledWeeklyService.class), PendingIntent.FLAG_NO_CREATE) != null);
  if (!weeklyAlarmUp) {   
    AlarmManager mgr = (AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(ctxt, ScheduledWeeklyService.class);
    PendingIntent pi = PendingIntent.getBroadcast(ctxt, 0, i, 0);                   

    Date date = null;
    try {
        date = (Date) formatter.parse("17-Mar-2014 13:10:00"); // This date & time will be an user input from some activity
    } catch (ParseException e) {
        e.printStackTrace();
    } 
    long triggerWeeklyTaskAt = date.getTime();
    long currentTime = System.currentTimeMillis();

    // Don't trigger the alarm is input date time is in the past, set it to next day but at the same time
    if (currentTime > triggerWeeklyTaskAt) {
        Calendar c = Calendar.getInstance(); 
        c.set(Calendar.HOUR_OF_DAY, 13); 
        c.set(Calendar.MINUTE,10);
        c.set(Calendar.SECOND,0);           
        c.set(Calendar.MILLISECOND, 0);
        c.add(Calendar.DATE, 1);
        date = c.getTime();
        triggerWeeklyTaskAt = date.getTime();
    }

    Locale locale = Locale.getDefault();    
    msgFormatter.setLocale(locale);
    Object[] objs = { "Dummy" };
    SchedulerLog.logInfo(ctxt, ctxt.getString(R.string.module_scheduler), msgFormatter.format(objs));       
    mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, triggerWeeklyTaskAt, PERIOD_WEEKLY, pi);       
  }

Can anyone tell me what is wrong in below code? How can I check what time it'll trigger alarm at?

Thanks

Was it helpful?

Solution

Your outer if statement looks a bit weird. Are you sure execution is making it inside of it? Throw in a Log statement and/or step through the code to make sure.

If I understand your logic, you're attempting to not create a duplicate PendingIntent. So if the PI already exists, you bypass the whole body of the if. The problem with that is that your alarm setup is inside the if statement too.

The reference page says "...even if its owning application's process is killed, the PendingIntent itself will remain usable from other processes that have been given it." So perhaps a matching PI still exists from a previous run? It might be better to always (re)create the PI, but use FLAG_CANCEL_CURRENT or FLAG_UPDATE_CURRENT depending on whether you want to update the particulars.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top