I have a service I am reusing (it a both a \"bound\" and \"started\" service) in my own app because it does a lot of useful data acquisition I\'m interested in. Everything
How would you solve this?
You never really stated what "this" is. I am going to guess that "this" is:
How do I have a service notify a foreground activity of mine if there is one, and otherwise raise a
Notification
(or perhaps do nothing at all)?
For that "this", use an ordered broadcast. As I wrote in a blog post from a ways back, here is the recipe for either notifying a foreground activity or raising a Notification
:
Define an action string you will use when the event occurs that you want to go to the activity or notification (e.g., com.commonsware.java.packages.are.fun.EVENT
).
Dynamically register a BroadcastReceiever
in your activity, with an IntentFilter
set up for the aforementioned action string and with a positive priority (the default priority for a filter is 0). This receiver should then have the activity do whatever it needs to do to update the UI based on this event. The receiver should also call abortBroadcast()
to prevent others from getting it. Be sure to register the receiver in onStart()
or onResume()
and unregister the receiver in the corresponding onStop()
or onPause()
method.
Register in your manifest a BroadcastReceiver
, with an <intent-filter>
set up for the aforementioned action string. This receiver should raise the Notification
.
In your service (e.g., an IntentService
), when the event occurs, call sendOrderedBroadcast()
.
If you simply want to notify one of your foreground activities, but do nothing if it is not in the foreground, skip step #3.
Here is a sample project that demonstrates this.
Is there a way for the service to know what applications are currently running?
You can ask ActivityManager
, but, frankly, that's asking for a fragile app.
Or perhaps currently in the foreground?
Not reliably.
Or how about currently bound to the service?
Only if you track it yourself.