0

I am having some trouble creating a NON-IPC service that allows adding/removing multiple listeners at various times, for example, I would like to be able to contact the service and "subscribe" to its events any time, or "unsubscribe" from it. The service wakes up every once in a while and sends an event to all subscribed listeners.

I have been looking at stackoverflow examples, googling, etc, particularly I found something similar here: android restful api

In that example, the suggestion is to use ResultReceiver to serve as a callback from a service. But in this approach, doesn't it mean that the service can only notify listeners sent to it as part of the first intent (i.e I cannot add/remove listeners whenever I want)?

Also, in that example, what happens if the activity gets destroyed by the OS for some reason, but the service still has a reference to the listener and tries to invoke it? The listener will try to perform some action on the activity, which no longer exists, right?

Maybe I am missing something... I'd appreciate some input if possible..

Tnx

Community
  • 1
  • 1
Sagi Mann
  • 2,967
  • 6
  • 39
  • 72

1 Answers1

1

First, 'sleeping' services are anti-pattern in Android. If you need to do something periodically, start your service using AlarmManager. Second, the service can be restarted at any time, so you cannot rely on 'subscribing' where you keep references to other components (activities mostly). If you need to send a notification to multiple activities, use a broadcast receiver. Activities can register for it statically (using AndroidManifest.xml), or dynamically (with code).

Nikolay Elenkov
  • 52,576
  • 10
  • 84
  • 84
  • thanks for your reply, I am not referring to a sleeping service - I am referring to a service that is currently performing some network activity, which may take a minute or so, and after that time, it needs to raise some event, that, hopefully some activity will catch. This is all happening inside the same app, not across app... My "missing link" is how to add/remove listeners as needed during that minute. Obviously the service should not hold direct references to listeners, but rather there should be some "message broker" in between... other (similar to a JEE Message Queue) – Sagi Mann Jun 21 '12 at 16:39
  • You can register broadcast listeners using `registerReceiver()`. The Android OS is the message broker, it takes care of delivering the events to the right receivers. http://developer.android.com/reference/android/content/Context.html#registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter) – Nikolay Elenkov Jun 21 '12 at 16:50
  • thanks, I am new to android, u gave me the step in the right direction :) – Sagi Mann Jun 23 '12 at 04:40