0

I am trying to set an alarm to call a method in MainActivity. I have used the method described here; the alarm fires but once it does it repeats about once a second.

I am using setExactAndAllowWhileIdle since the alarm is needed only every hour or so (actually it doesn't need to be exact, I could use setAndAllowWhileIdle instead but that gives the same problem).

My Alarm class is pretty simple:

public class Alarm extends BroadcastReceiver
{
  static MainActivity main = null;
  public Alarm()
  {
  }
  public Alarm(MainActivity ctx)
  {
    main = ctx;
  }
  @Override
  public void onReceive(Context context, Intent intent)
  {
    if (main != null)
        main.alarmAction();
  }

}

In OnCreate() for MainActivity I have

    alarmReceiver = new Alarm(this);
    IntentFilter alarmFilter = new IntentFilter("Alarm");
    registerReceiver(alarmReceiver,alarmFilter);

and then I have methods:

public void SetAlarm() {
    alarmStarted = true;
    Intent i = new Intent(this, Alarm.class);
    i.setAction("Alarm");
    PendingIntent pi = PendingIntent.getBroadcast(this, 1001, i, 0);

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.cancel(pi);  // tried this to solve the problem but probably not needed
    am.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME, 1000 * 60 * 10, pi);
}

public void alarmAction() {
    if (!alarmStarted)
        return;
    SetAlarm();
    // will be more stuff here but this is minimum required to show problem

}

The flag alarmStarted is set from a button press.

Android Studio is giving me a memory-leak warning about the use of static in static MainActivity main = null, but without this main is always null in onReceive. I don't know if the repeating alarm issue is connected with this or not.

quilkin
  • 874
  • 11
  • 31
  • 1
    Have a look at [the docs for that method](https://developer.android.com/reference/android/app/AlarmManager#setExactAndAllowWhileIdle(int,%20long,%20android.app.PendingIntent)). The second argument needs to be a clock time at which to fire the alarm, not an interval to elapse until then. – Mike M. Dec 08 '21 at 17:18
  • Thanks, you're right of course. Missed that. If you'd like to add it as an answer I can mark it as such. – quilkin Dec 08 '21 at 22:04
  • No problem. I'm good, however. :-) Nothin' huge. Thanks, though. I appreciate the offer. Cheers! – Mike M. Dec 08 '21 at 22:05

0 Answers0