1

I am using an alarm manager with inexactRepeating starting a pendingIntent.

Works great - only problem is that the service is running every time the app is started, after onDestroy (ie orientation change, manually swiping app in recent).

I have it set to 20 min intervals, and it does so as long as I dont onDestroy the app - the onCreate automatically starts the service which screws up my timing. The service is only ever called, once, through the alarm manager.

How do I check to see if the app needs to run it? Boolean of is running inside the service in shared preferences or something?

SQLiteNoob
  • 2,958
  • 3
  • 29
  • 44

2 Answers2

2

You could place the AlarmManager in a class that your Application class creates once during application startup. Then you will ensure that your app only creates one instance of the AlarmManager when it first starts up.

In other words, create a class that extends Application, and in its onCreate(), create an instance of your AlarmManager class and store that instance in that Application class. Inside the class that holds your AlarmManager, in its constructor create a new instance of AlarmManager. Then in your Application class, you could create a getter method so that any of your app's other activities or fragments could retrieve and use that one instance of AlarmManager.

Note that there is some debate as to whether you should use the Application class to store global application state, as opposed to a static singleton.

Community
  • 1
  • 1
JDJ
  • 4,298
  • 3
  • 25
  • 44
  • It's a possibility, but is it really not too much overhead? I am using the repeatingservice to record sensor data at regular intervals, and I just need the service to start, and not to run every time the service is running. Thanks for the excellent explanation and unbiased mentioning of the debate- everyone ought to consider it. – SQLiteNoob Jun 30 '14 at 14:22
2

The best answer was on this site at this link:

How to check if AlarmManager already has an alarm set?

The idea is to use a boolean to determine if the alarm has already been set:

        boolean alarmUp = (PendingIntent.getBroadcast(context, MyApp.TIMER_1, i, 
                          PendingIntent.FLAG_NO_CREATE) != null);
Community
  • 1
  • 1
SQLiteNoob
  • 2,958
  • 3
  • 29
  • 44
  • Or use the singleton advice below - I would have, if this app was extensive enough to require me to use a singleton. – SQLiteNoob Jun 30 '14 at 16:39