Reputation: 69
I am new to android development and having trouble understanding how I should use service's
and more specifically which kind. I am developing an simple system that only will do to things. One of those to is to continuously ask a server simple telnet
questions. The answer to these questions should be prompted on the screen.
So to simplify my question. What kind of service should I prefer? bound, intent service
etc?
I presume it has to run a own thread since it is suppose to do network comm, so how should I do that.
Finally and most importantly, how do I supply/give the MainActivity
the information the service has gathered and post it on the screen?
Upvotes: 0
Views: 72
Reputation: 496
Here is a quick summary on services in Android, hopefully this will help in deciding what approach to go. Reading Android Services is highly recommended
Android Service
Upvotes: 0
Reputation: 16043
What kind of service should I prefere? bound, intentservice etc?
A bound service runs only as long as another application component is bound to it. With other words, if an activity bounds to that service, and later that activity gets finished, the service also gets destroyed.
So, first decide the behaviour of the service you want to have. Do you want it to be destroyed when the activity bound to it gets destroyed? If yes, then perhaps a bound service is the right thing to do, if not then use a started service instead which can run in the background indefinitely, even if the component that started it is destroyed.
I presume it has to run a own thread since it is suppose to do network comm, so how should I do that.
Yes, you are right. You can use the Service
class and create a thread inside it that will do the heavy work, or, you could simplify things by using an IntentService
which provides its own worker thread.
Finally and most importantly, how do I supply/give the MainActivity the information the service has gathered?
If you decide to go with a bound Service
, then you'll be able to communicate with the service through a so called binder object. On the other hand if you go with IntentService
then you could use a ResultReceiver, or a BroadcastReceiver to send the result back.
Suggested readings:
http://developer.android.com/guide/components/services.html
http://developer.android.com/guide/components/bound-services.html
Upvotes: 1