views:

80

answers:

2

Is there a native android way to get a reference to the currently running Activity from a service?

I have a service running on the background, and I would like to update my current Activity when an event occurs (in the service). Is there a easy way to do that (like the one I suggested above)?

A: 

You might check out ActivityManager, also take a look at DroidFu. They keep a WeakReference to the active context in their overridden Application.

schwiz
+1  A: 

Is there a native android way to get a reference to the currently running Activity from a service?

You may not own the "currently running Activity".

I have a service running on the background, and I would like to update my current Activity when an event occurs (in the service). Is there a easy way to do that (like the one I suggested above)?

  1. Send a broadcast Intent to the activity -- here is a sample project demonstrating this pattern
  2. Have the activity supply a PendingIntent (e.g., via createPendingResult()) that the service invokes
  3. Have the activity register a callback or listener object with the service via bindService(), and have the service call an event method on that callback/listener object
  4. Send an ordered broadcast Intent to the activity, with a low-priority BroadcastReceiver as backup (to raise a Notification if the activity is not on-screen) -- here is a blog post with more on this pattern
CommonsWare
Thanks, but as I do have a looot of activities, and don't want to update them all, I was looking for an android way to get the foregroundActivity. As you say, I should not be able to do that. Means I have to get my way around this.
George
@George: What you want wouldn't help you, anyway. As you point out, you have "a looot of activities". Hence, those are all separate classes. Hence, there is nothing your service can do with them without either a massive if-block of `instanceof` checks or refactoring the activities to share a common superclass or interface. And if you're going to refactor the activities, you may as well do it in a way that fits better with the framework and covers more scenarios, such as none of your activities being active. #4 is probably the least work and most flexible.
CommonsWare
Thanks, but I have a better solution. All my activities extends a customised BaseActivity class. I have set a ContextRegister that registeres the activity as current whenever it is on the foreground, with literraly 3 lines in my BaseActivity class. Still, thanks for the support.
George
@George: Watch out for memory leaks. Mutable static data members are to be avoided in Java wherever possible.
CommonsWare
I have tightly encapsualted the object, though I will indeed keep this in mind. Thanks.
George