How do I use the Service feature in Android - android

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?

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

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
"A Service is an application component that can perform long-running
operations in the background and does not provide a user interface"
runs on the main (UI) application thread.
it is given preference over activities in termination when resources
are low
it is not intended to interact directly with an activity/fragment (an activity may be destroyed at any time) no simple callback ability due to above... however there are some ways to address this using Intents, Handlers and Messages
an activity can be bound to a service which
basically gives an instance of the service to call methods, the methods will run on the main thread, a suggested way to use a separate thread, is to use Executors

Related

Bound Service vs Unbound + singleton for communication

I have a service, I need to communicate to with it (one service - many fragments/activities). There are two options for this:
Have a singleton that controls the service - starts it and then binds to it (using the app context)
Have a singleton that controls the service - starts it, the service when ready registers back as a delegate to the singleton (in a WeakReference)
Solution no 2 seems simpler to me, but whenever I read about communication with services there is the concept of the bound service.
Is there any benefit of having a bound service instead of the service registering itself as a delegate (and unregistering with onDestroy)?
Edit 1: The service is to keep the communication alive, it's expensive to set up a new communication channel. Even if no one requested any data it should keep the channel alive (heartbeat).
The service is foreground, it should run even if the activity that requested the data gets killed by the system. The next time it is created the data will be there.
The data requested by one screen might be useful for some other (therefore has to be stored in a singleton).
Bound and unbound services are both usable patterns and you should pick whatever pattern is better for you use case.
You should pick bound service if you want your service to have the same lifecycle as the components that bind to it. If you need an independent service use an unbound version.
The only benefit of one approach versus another is the simplicity of implementation.
In you case, I think you need the service only while there are running activities and fragments, then the easiest way, in my opinion, would be to make a bound service and make every activity bind to it. With that, you'll get a simple communication interface between you activities (and fragments, since they have access to containing activity) and your service.
The benefits of this approach are:
the service will stop itself if all activities unbind and start itself when first activity binds to it.
you won't need to track all running activities in the singleton and manually unbind
you won't need to maintain a singleton manager, less code -> less bugs
sometimes onDestroy can be skipped by the system and you can leak the service with the 2 approach.
Since you need your service to be running the correct option will be to use a started service and make each activity bind to it when needed. It's a common pattern.
Started service will run until you explicitly stop it or it stops itself, you can have a singleton manager that will be responsible for that.
But at the same time you can communicate with the service from your activity using binding.
So basically comparing with the first suggested approach, you'll need some instance that will start and stop the service, but the communication between activities and service will be the same - using binding.
Yes, using a bound service in Android is a much better option when communicating with Views like Activities/Fragments. This is because of the following reasons,
It runs synchronously.
You can have more control on the service data when to show on UI thread of the view. You can choose when to call it in async/sync way.
LocalBroadcastManager only runs Asynchronously.

Why to use Android Bound Service?

I am curious to know why would you use Bound Service for 2 way interaction between Activity and Service when you can do the same kind of interaction with Started Service using local broadcasts and receivers defined in both Activity and Service
It will be helpful to know the pros and cons of each implementation.
I couldn't find any clear answer to this anywhere.
Using a bound Service is much more flexible. You can define methods on the Service (using AIDL) that return immediate results (synchronously), which you cannot do using LocalBroadcastManager. Using LocalBroadcastManager requires that you use your Service in a completely asynchronous way. This decouples the initiation of a service action with the return of the results (callback) which can make your code more complicated and more difficult to understand. Asynchronous use has some benefits, and there are places where you should use it, but if you have a bound Service you can choose exactly when to use synchronous calls and when to use asynchronous callbacks.
Also, the use of AIDL allows you to exactly describe the signatures of the services's method calls. If you use startService(Intent), you cannot guarantee that the caller will provide the correct arguments in the passed Intent, so you need to rely on the caller to "do the right thing" and/or you need to add a lot of additional argument verification.
Don't forget the comment from #CommonsWare about how LocalBroadcastManager only works if the Service is running in the same OS process as the rest of your app (which makes it unsuitable for programming things like system services, which are not running in your OS process).
A service is a component that runs in the background. It works to perform long-running operations without needing to interact with the user For example, a service might retrieve data over the network without stopping or blocking user interaction with an activity of an app or user may play music in the background while the user is in a different application. A service can be of two types or states:
Started: Once started, a service can run in the background indefinitely, even if the component which is started, is destroyed. A service is started when an app module or component, such as an activity, starts it by calling startService(). For example, retrieving contacts from phone book using service when Splash Screen starts.
Bound: A bound service offers a client-server interface that allows components to interact with the service, get results, send requests and even do so across processes with interprocess communication (IPC). A bound service is bound, when an app component binds to it by calling bindService().

About android service-activity data transceive and ServiceConnection

There are several ways to connect to Service to Activity. I am only interested in local service and my LocalService will stand there untill user stops it(which also means end of app). I might know things wrong, if so please correct me.
On the reference page, it is stated that in order to use methods of local service directly, we should use ServiceConnection. After binding, we can have a reference to LocalService class, and we can use methods of this LocalService directly. AFAIK the methods we call using this reference run on main thread with relevant Activity.
The thing that confuses me, what if I use skeleton structure and access LocalService's methods by directly its static reference (ie. by LocalService.getInstance()). Well, I have already used it and did not face any problem, but still I am not sure which one is better, and why.
Thanks in advance. I might add additional info if requested.
edit:
In my previously mentioned solution, no activity is keeping a reference to the LocalService.
It is used to
start some LongRunningAsyncTasks(which are all halted and reference-nullified before service stop),
update the app Notification,
get getFilesDir(),
to keep an enum value (whose reference is not kept elsewhere, it is just used for comparison) in order to access from everywhere(not worthy of using SharedPreferences).
show some toasts
aware of static references of activities and services because they can be a reason of memory leak. if you don't want your service run in main process, then extract it into another process and work with service connection.
If you don't need any feedback from service, then just don't use connection and simply use startService() with several commands which will be executed in onStartCommand() method of the service.
If you need feedback from service, but not frequently, then use startService() and feedback from service with sendBroadcast() or through Handler class.
If you need feedback frequently (for example update slider of media player), then it's better to use service connection.
Remember that your service can be killed anytime without executing method onDestroy() and without any notification, that's why keeping static reference is not good idea.
It appears from what you are saying that you probably don't need a Service at all. Looks like you are not doing any long-standing task in your LocalService. If that's the case, you can as well use AsyncTask or Handlers and be done. The motivation to use a Service (Local or otherwise) is to do some long standing task inside it and not stall the main UI thread. If your tasks are not gonna take up too much time, then you don't need a Service.
The Service does run on the main thread by default. Unless it's an IntentService where a worker thread is created for you automatically and all tasks are queued and handled one at a time in this worker thread. Otherwise, it's your responsibility to create a separate thread for your service tasks.
So, first analyze if you really need a Service. If your task can quickly get executed, then don't bother having a Service even.
Hope that helps.

Calling a lengthy Service method from an Activity - Best Practice

I'm developing an app with a service that forwards calls to a web-service, and a few activities that place those calls. The activities need to process the results of those calls. For example, I have a writeComment method on the service, that accesses the web-service and returns some information about the newly written comment.
Right now I let the Activity take care of all the threading. The Activity binds the service, and then uses an AsyncTask that calls the bound service's writeComment method.
All works well as long as the Activity isn't stopped while the AsyncTask is running. If it does (easily happens when flipping the phone), the AsyncTask dies a violent death when trying to update the UI in onPostExecute. I'm not entirely sure how to fix this - I do need to let the user know the server has been updated.
If I go the other way around, and register a callback with the Service, I'm still a bit stump, because I need to notify the Service the Activity has changed - I need to tell it not to notify me in the first Activity's onDestory, and reregister in the second Activity's onCreate. And I need to handle the case where the asynchronous task completes after onDestroy and before onCreate.
What is considered Best Practice in this case?
Thanks,
Itay.
My intuition tells me to let the service handle the threading. Services are far less transient (although still transient to some degree) than activities and therefore you'll have less issues of threads trying to interact with a Context (be it an Activity or a Service) that's no longer there. Have you looked at the IntentService class? It handles a lot of the threading for you.
In my app, I have a long-running service and Activities that need to render data in the service. The service also pings the Activities when there is a change but the Activity can also query the service. The way I approached this was two-fold.
Firstly, I bind my activity to the Service in order to send messages from Activity to service.
Secondly, the Service sends notifications with Broadcasts and the Activity listens for those broadcasts. I set that up in the Activity onResume and tear it down in the onPause. I think this is the part that you're missing.

Android - Run in background - Service vs. standard java class

In Android, if I want to do some background work, what is the difference between
Creating a Service to do the work, and having the Activity start the Service
VS.
Creating a standard java class to do the work, and having the Activity create an object of the class and invoke methods, to do the work in separate thread.
Doing your own threads is overkill, there are solutions for this, so you don't have to worry about the hard parts of concurrency. Have a look at AsyncTask or IntentService. If you go for a service please keep in mind that your service can be killed at any time.
Well, Android provides some useful methods for making worker threads easily. Look at the Looper class definition. It allows you to send events via a Handler to be executed one after another in another thread or transmit messages between different threads.
A service is nothing fancy. Creating a Service is just a way of telling the OS that you need to do some work even when your Activity is not visible.
Depending on the application you're building it might not be an option.
Nearly every network application will have some of its functionality on a Service to allow the user change active Activity while something is being downloaded.
In an RSS reader, for example you can click 'Update all' and, depending on the current data connection, it might take a bit longer than you wish. So if you want the user to be able to get back to the Home screen and do anything else while the files are being dowloaded you'll have to use a Service.
A Service allows you to run tasks on the background while the user is not on your Activity. This doesn't mean it'll be running all the time. Check the Service lifecycle.
BTW IntentService is a service.

Categories

Resources