Android; Using a Service to subscribe/unsubscribe to an Observable object, good idea?
I have a requirement, whereby when a user clicks a button, then an object needs to be observed. When the user clicks that button again, the observation stops.
My initial thought is开发者_StackOverflow中文版 to have the button bound to a method in the activity using the onClick="myMethod"
in the layout file.
When this method is invoke it will call startService()
which starts observing the object. By this I mean it registers the service as an observer.
When the button is clicked for a second time, it calls the stopService()
method which un-registers the service as an observer.
My thoughts for using a service is so the observation; and subsequent actioning is taken off the UI thread. Is this a reasonable approach or is there something in the Android SDK that could do this easier?
My thoughts for using a service is so the observation; and subsequent actioning is taken off the UI thread.
Only if you fork your own thread, and only if the "observation" supports alternative threads. Services are in the "background" from a UI standpoint (they do not draw on the screen directly), but they are not in the "background" from a threading standpoint by default.
Is this a reasonable approach or is there something in the Android SDK that could do this easier?
That is impossible to answer given what you have written above. You seem to think the button is important -- probably, it's not. What probably is important is what this "object" is that you are "observing"...and you didn't say what it is.
If your service will reliably unregister itself in stopService()
, you should not run into garbage collection issues with this approach. However, threading with respect to the observer/observable pattern usually is the responsibility of the observable -- in this case, the mysterious "object".
I agree with Murphy however a small point i think i should give you: 1. what are you doing when the activity is destroyed ? paused ? 2. if the object u are observing is generating events that you need to observe you have to think what happens to them in all situations, if the observer object dies with the activity, i think u are better off with async task or local thread, in any case you will also have to discover that the activity was destroyed in your service in order to GC the observed object or kill the service too in the Activities onDestroy.
精彩评论