2

I'm using alarm manager to setup pending intent, so my code gets executed even if app is closed

manager.setRepeating(AlarmManager.RTC, System.currentTimeMillis() + interval, interval, pendingIntent);

The problem is that it also works when app is open, i need to configure it to work only if app is closed. Is there a way to configure it through alarm manager or from the activity?

Edgar Zakaryan
  • 576
  • 5
  • 11
  • which BroadcastReceiver are u using the manifest one or the manual code one? – MOSO Oct 20 '14 at 07:34
  • 1
    Alarm Manager doesn't work when app is closed. You need to use STICKY SERVICE for this which will run in background... – Riad Oct 20 '14 at 07:37
  • create background service for this and check if youractivity is in front than dont execute your code.. – Naveed Ali Oct 20 '14 at 07:49
  • @NaveedAli that's how i do currently, my background task gets fired on each interval, and i check if app is running or not, but i thought there would be way to avoid running background activity if app is open – Edgar Zakaryan Oct 20 '14 at 07:52

1 Answers1

1

Alarms operate outside the scope of your application, so you need to manually cancel them if you no longer need them. You can use the cancel() method of AlarmManager to accomplish this. Unfortunately I don't think there is an easy way to understand if your application is closing. On way could be using ActivityLifecycleCallbacks. Check this answer for more informations. As you can read there

Just check if the number of stopped activities is equal to the number of started activities. If they're equal, your application is being backgrounded

At this point you can set the alarm. Conversely

If there are more started activities, your application is still visible. If there are more resumed than paused activities, your application is not only visible, but it's also in the foreground

when in this situation, you can use the cancel() method of the AlarmManager. Bear in mind that all alarms are cancelled whenever the device is rebooted.

Community
  • 1
  • 1
Mavi
  • 71
  • 4
  • well said mavi. Actually when machine rebooted, the Background Service aligned with apps get stopped until it starts again. @Edgar: "to avoid running background activity if app is open"- check the application is_running on the service and then dont do the task if it is running. – Riad Oct 20 '14 at 09:14