Android Service - android

Please explain an Android Service. How does it differ from an Activity? Does it depend on an application state such as running in the foreground/background?

From the Android Developer's SDK reference for Service:
A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.
It is very important to note
that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work.
This is in contrast to an activity which is best understood as something a user directly sees and interacts with (a UI.)
A service, as mentioned above, can be used for longer-running operations that will continue even if you have no foreground activity, but they can, and eventually will be killed by Android's lifecycle if left in the "background" state. If you need your service to continue running as a single instance without being killed and restarted, I would recommend placing startForeground(int id, Notification notification) in your Service's onCreate method and stopForeground(boolean removeNotification) in your Service's onDestroy method.
For example, I have an app that uses a foreground Service to record accelerometer data all night while the android device is next to the user's body. Though it is not required to be active, I also have an Activity that broadcast an Intent to a BroadcastReceiver inside the Service which tells the Service that it should also broadcast an Intent with accelerometer data as extras to a BroadcastReceiver inside the Activity.
Code:
SleepActivity
SleepAccelerometerService
Good luck and let me know if you need any more information!

a Service is a context similar to Activity but has no GUI.
Important: A service doesn't run in a new thread!
Read about Service and also check out How to always run a service in the background?

Related

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().

new to android - understanding the use of the service

I have been going through this very short tutorialand I am confused as to what is the function of the service. I am also confused as to what is the function of the broadcast receiver.
I tried to do some research and here is what i understand:
- services run in the background, but... i don't understand why we need something
to run in the background to make the phone wake up at a certain time.
I "think" the broadcast receiver acts as some kind of catcher's mit, in that
when the pending intent is launched at a specific time, it catches it then
launches the service... how close am I to the truth ?
As i think that services are used for long running tasks and especially in those cases that run when your main activity is not running.
For this functionality we can use threads this make us to say that a thread is created inside our activity and it can't be active outside of the our main activity,
that is the drawback that's why we have services .
Document URL
Services can be used to run long running tasks independent of your screen flow. For example, consider your application require to communicate with a server via socket throughout its running duration, you can start a service to handle this. Imagine that against starting the socket and making connection at the start of every activity, and clean up when that activity stops.
Services by default run in the main thread. But you can start separate threads in a service context, just like you do in an Activity. If your background task can overlap across multiple activities, then it is better to start it in a Service context because every Thread/AsyncTask created retains the context that it is running. In that case your Activity will be retained even if user navigates to another activity because a thread started from that Activity is already running. If Activity is retained, it might prevent all its views, images getting garbage collected.
What Services can't do is to directly alter UI components. For that it needs to communicate with the currently running Activity context. In short, if your non UI task does overlap the life time of a particular Activity, it is better to shift that task to a Service.
What is the function of the service ?
A service is a component which runs in the background without direct interaction with the user.
As the service has no user interface, it is not bound to the lifecycle of an activity.
Services are used for repetitive and potentially long running operations, i.e., Internet downloads, checking for new data, data processing, updating content providers and the like.
TO READ: Service
What is the function of the broadcast receiver ?
Broadcast receivers are the second kind of component. Like services, they only exist in the background and don't interact with you directly. But unlike services, they can't stay running or perform long tasks: they exist to respond to events. And unlike activities and services, more than one broadcast receiver can be started in one go.
Each broadcast receiver can react straight away, for example by creating a notification, or it can start a service or an activity to take further action. As soon as the broadcast receiver has handled the event, it is stopped and will not run again until another similar event is broadcast.
TO READ: BroadcastReceiver
I don't understand why we need something to run in the background to
make the phone wake up at a certain time ?
We don't want that the application should necessarily be in the foreground to wake the phone up.
Moreover we want notifications in the background.
We started the service. Now even if we close the application, you can get the phone wake up notification. This is so useful.
Services are great to interact with a user through notifications (a way of alerting a user about an event that he needs to be informed about or even take some action on getting that information). Many a time, applications will need to run processes for a long time without any intervention from the user, or very rare interventions. These background processes need to keep running even when the phone is being used for other activities / tasks.
To accommodate for such a requirement, android has introduced the "Service" component.
It runs in the background until it stops itself. This means that a service could be keeping your phone awake (using a wake lock), running down the battery, or using lots of network data, without anything showing on the screen.
I "think" the broadcast receiver acts as some kind of catcher's mit,
in that when the pending intent is launched at a specific time, it
catches it then launches the service... how close am I to the truth ?
Correct, they are meant to respond to an intent (usually one sent by a service or a system event), do something, and be done. When an intent is broadcast via sendBroadcast, it will be sent to all receivers that have matching intent filters.
Service - is a component of android, which runs in the background with out any UI. By default service will run in Main thread only.
Thread - is not android component, but still one can use thread to do some background task. Using thread in place of service is discouraged

Foreground processes in Android

With respect to Process lifecycle, Android system tries to maintain an application process for as long as possible, but eventually needs to remove old processes to reclaim memory for new or more important processes. To determine which processes to keep and which to kill, the system places each process into an "importance hierarchy" based on the components running in the process and the state of those components. Processes with the lowest importance are eliminated first, then those with the next lowest importance, and so on, as necessary to recover system resources.
One of the classification is :
Foreground Process : A process that is required for what the user is currently doing. A process is considered to be in the foreground if any of the following conditions are true:
1. It hosts an Activity that the user is interacting with.(the Activity's onResume() method has been called).
2. It hosts a Service that's bound to the activity that the user is interacting with.
3. It hosts a Service that's running "in the foreground" —the service has called startForeground().
4. It hosts a Service that's executing one of its lifecycle callbacks (onCreate(), onStart(), or onDestroy()).
5. It hosts a BroadcastReceiver that's executing its onReceive() method.
What can be real life examples of scenarios given above I am asking this because it will help me and others as well in differentiating between this situations.
1)THe app that is currently on top of the stack (the one the user is using)
2)An app with an Activity that has called bindService on any service. The idea is that if it killed that service, it might lose data. An example of this would be a facebook app, which has a background service to fetch data every so often. If the user has it open, it would qualify
3)This is a service that has declared that its feeds data to a UI. An example of this would be a facebook app where the user didn't have an activity with it open
4)This is a service that's just starting or just finishing. This would be pure luck to have happen, but its basically saying it will try to let it start up or finish cleanly before killing it
5)This is any app that's currently responding to an event. An example would be an SMS app that was just notified of an incoming SMS and needs to deal with it. It will be allowed to run until its done, because doing otherwise may lose data.

How do I use the Service feature in 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

Long running Android 'service'

I have an Android app, in which Activities fire long running operations that run in the background. These operations interact with the Activities when done. I'm developing a component that handles the Activity/Long-Running-Task coupling, taking care of activities being destroyed and recreated.
Right now that component is implemented as an Android service. The activities call bindService and use the resulting IBinder to start and track tasks. I decided against using startService, because I prefer the richer API possible through a Java interface.
Now the problem. Activity A start ups, binds to the service and calls serviceApi.runTask(...). Activity A is then destroyed (because the user flips the phone, for instance) and recreated as Activity A'. A' then binds again to the service, announces its existence and everything should be running nicely.
Except that my Service gets destroyed. When Activity A is destroyed, it unbinds from the service. Android sees there are no more clients, and kills the service. When Activity A' is created, the service is created again, and I lose everything the old service had.
The only solution I can see is using a singleton for the service. And then it doesn't really have to be an Android service, just an instance that's accessible to everyone. Is that frowned upon in Android? Is there a better design that fits this problem?
Editted: Even if I call startService and then bind to it, nothing guarantees that the service instance will exist as long as the application is running. Android can kill sticky services if resources are low. Killing the service will cause the application to malfunction, and I can't have that.
Even if I call startService and then bind to it, nothing guarantees that the service instance will exist as long as the application is running.
Correct.
Android can kill sticky services if resources are low.
Also correct. All "sticky" means is that Android might restart the service.
Killing the service will cause the application to malfunction, and I can't have that.
It is impossible to create a service that is guaranteed to run forever. For starters, users can get rid of your service whenever they want, because users detest developers who have pointless services that run forever. Writing everlasting services is necessary only in very few cases; otherwise, it's just sloppy programming.
The only solution I can see is using a singleton for the service. And then it doesn't really have to be an Android service, just an instance that's accessible to everyone. Is that frowned upon in Android?
Singletons (a.k.a., static data members) will go away when the process is terminated. The process will be terminated eventually, particularly if there are no active services and none of your activities is in the foreground..
Call startService and in onStartCommand return START_STICKY. It should keep the service going.
You may also want to look into foreground services:
http://developer.android.com/reference/android/app/Service.html#startForeground(int, android.app.Notification)
Yo have to create persistent service. Refer to this manual.
In a few words - don't call bindService, call startService.

Categories

Resources