views:

34

answers:

1

I've got an Android app which has a periodic background Service. I want this Service to react differently depending on whether any Activities in my application are open. The issue is that the Service just keeps itself running via the AlarmManager making it on kind of on a separate "track" from the Activities, so I don't know whether the application is open when it runs.

The best solution I can think of is to flip a boolean on/off whenever onResume() or onPause() is called in all my Activities, but this seems like a lot of footwork. Is there a simpler, more elegant solution?

A: 

Is there a simpler, more elegant solution?

Well, it depends a bit on what "react differently" means.

Let's suppose you want to raise a Notification if your activities are not in the foreground, but you want to pop a dialog if an activity is in the foreground.

In that case, you need some communication path from the service to the activity anyway. So, register a callback (supplied by the activity) with the service in onResume() and unregister it in onPause(). Your service uses the callback if one exists; if there is no callback, it raises the Notification.

You could accomplish the same thing with a broadcast Intent (register/unregister the receiver in the activity in onResume()/onPause()) if you wanted.

CommonsWare