Search code examples
androidalarmmanagerandroid-alarms

AlarmManger constantly start and stop, bad practice?


I have an application that does some data processing, then notifies the user in the status bar if any new items are found. The process runs as an AlarmManager at a set amount of time. Everything works fine, but I'd ideally not like the user to be notified while they are actively using the application, which means the AlarmManager should basically be suspended. The only solution I could think of is constantly start/stop the alarm in the main Activity's onResume method similar to this:

@Override
public void onResume()
{ 
      AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
      Intent myIntent = new Intent(this, AlarmReceiver.class);
      PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0);
      alarmManager.cancel(pendingIntent);
      alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 600000, 600000, pendingIntent);
}

This isn't foolproof, but the best solution I could think of. Just wondering if that is bad practice or if there is a better solution? Thanks.


Solution

  • Just have your AlarmReceiver (or the Service it invokes) check to see if the app is visible or not. You need to share some state between your app and the AlarmReceiver/Service. You could have a base Activity that tells your AlarmReceiver/Service that is in the foreground during onResume and that it is in the background during onPause. Then the AlarmReceiver/Service can simply check this state when the alarm goes off and use that to decide if a notification should be shown or not.