Error when resetting alarm with Alarmmanager right after cancelling it

Asked

Viewed 273 times

0

I have an alarm set to wake up at a certain time and repeat every five minutes. But after a few repetitions, I automatically set the cancellation of the same, that is, call the method to cancel "cancelAlarm();" and then call the method setNewAlarm();

But when it comes to the second method, it returns to me the following error:

E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-11525
java.lang.IllegalStateException: System services not available to Activities before onCreate()

I would appreciate an illustration of something I’m not supposed to see. Thank you. Below the code:

File1.java

File2 f2 = new File2();
File3 f3 = new File3();
if (lunchHour == hr && lunchMinute == minut && secs == 0) {  
    f3.cancelAlarm(context);
    f2.setNewAlarm();
} else {
    if (finishWorkHour == hr && finishWorkMinute == minut && secs == 0) { 
        f3.cancelAlarm(context);
        f2.setNewAlarm();
    }
}

File2.java

public void setNewAlarm() {

    int afterLunchHour = 17;
    int afterLunchMinute = 58;

    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent myIntent = new Intent(SentadoAlmoco.this, MyReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(SentadoAlmoco.this, 0, myIntent, 0);

    //Set the alarm to start at a specific time
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(System.currentTimeMillis());
    cal.set(Calendar.HOUR_OF_DAY, afterLunchHour);
    cal.set(Calendar.MINUTE, afterLunchMinute);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000 * 60 * 5, pi);
}
  • Shows more of the code. Only the functions called does not help much.

  • @Lucasnunes. FYI

  • At what point is calling this code that handles file and calls the setNewAlarm? Beware because the error is clear, is calling this code before calling the onCreate of the superclass of its context.

  • @Wakim, in this code snippet, I omitted the onCreate method ... In fact, I want to know, if it is possible to cancel the current Alarm set and then without setting a new Alarm?

  • Yes, it is possible. I recommend you use Services to manage alarms!

  • @Felipebonezi Blz

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.