new to android - understanding the use of the service - android

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

Related

Android service that doesn't close with application

I have been searching the net for hours. I am trying to make an application that has a UI interface and a service running in the background for SIP phone communication, kind of like Skype.
The UI starts and stops the service based on UI events, and the service stays logged in with a internet server in the background. I have found many articles talking about running the service on a separate thread(done), using startService as opposed to binding the service(done) but whenever I use the task manager to kill the application as a user might, I get an error popup saying my application has crashed and the service no longer runs.
How do programs like Skype, Facebook, or email clients do this?
Do I have to run these as separate applications using implicit intents?
Is there some settings I have to set in the manifest file other than declaring the service and it's name?
Better yet, is there a link to some page or source example using this kind of service?
EDIT: Sorry, I guess I wasn't clear. The service is stopping, and I don't want it to. I am trying to keep the service running in the background even after a user kills the application with the application manager.
One of the more confusing things with Service is that it is not run in a separate thread by default. Calling startService() as opposed to bindService() makes no difference in this regard. However, the binder mechanism will cause the Service exposed methods to be called in arbitrary thread context. In both cases, your Service is part of your application's process. If you kill it via the task manager or it crashes then the Service dies as well.
When you kill the app via the task manager and it pops up the message about the app dying, you have something misbehaving. Check logcat and it will point you at exactly where the crash happened.
If you need to have your Service running regardless of the UI, then don't stop the Service when your UI exits. You will still call startService() when your UI starts to re-connect (and possibly re-start it), but don't stop it unless you really want it stopped. Starts do not "stack". If something calls start 5x it doesn't take 5 stops to terminate the Service, only 1.

Keep Service in sync with Application

I am wondering what is the best way to keep a service running while the application is running (may be in background) and then the service stopping when the application has ended (the application in this case has completely stopped, not in the background).
Another sub-question is: How to stop a service when application stops?
I realize one solution is to use BoundServices but is this the best way or good enough?
For example if an activity binds a service and then the system kills the activity and brings
it alive again then how will the service behave? Or are there other issues I am not aware of?
What would be the best way to implement this? Thanks.
Check out http://developer.android.com/guide/components/bound-services.html.
A bound service is the server in a client-server interface. A bound service allows components (such as activities) to bind to the service, send requests, receive responses, and even perform interprocess communication (IPC). A bound service typically lives only while it serves another application component and does not run in the background indefinitely.
You have two options to start the service:
1. bindService() to activity
2. startForeground() and bind while it runs
Option 1 will only run as long as the activity is in view and the runnable active. (example use would be to use service to download a file)
Option 2 will run as long as the application is running (even when the activity is in the background) This option requires that your service be listed in the notification bar.
You can have a service stop itself by calling stopSelf(int) (I dont think this works if a activity is currently bound) or you can call stopService() from an activity.
As for the system killing the activity question.... Without knowing what your service will be handling its hard to give advice on how to handle this situation. For the most part a service running in the foreground will be the last resource the system will try to reclaim. If the system kills the activity the services onDestory method will be called where you should do some clean up so that the next time it starts you can continue in a safe manor.
http://developer.android.com/images/service_lifecycle.png

Where I should use Service , AsyncTask and Broadcast Receiver?

I'm in little bit confusion where in what case I need to use application components like Service, asyncTask and Broadcast Receiver.
Can any one explain what the exact difference between these there and where I need to use these components?
AsyncTask is a friendly way to create a new thread that performs some work asynchronusly.
A Broadcast Receiver is something like an Event Handler for system events. It can run in
background and perform an action when something happens, like turning the phone off or turning wifi on..
A Service is just an app that works in background (like a daemon) and serves information to an app or just performs tasks.
Sorry for my English, I try to let me understand but it is not my mother tongue
I will get straight to where I have applied these three in my projects so far:
1.Service:Something you want to perform in the background without any user interaction.For instance fetching location data continuously or sending some data continuously to your server.You can also use services to perform tasks every few time units.For example sending ten minute background updates.
2.AsyncTask:Making a new thread of execution.Best use I have encountered so far is calling a web service..I did the following using an AsyncTask for web service calls
1.Display Progress bar in onPreExecute()
2.Perform my web service calls in doInBackground(Params...)
3.In onPostExecute(Result) update the UI or do some other stuff with the response from the web service.
3.BroadCastRecievers are like global recievers for your app.They can listen for both System events like a phone restart or a custom event within your app.I used them for starting a service when the phone was restarted,which stopped when we switched off the phone.
Let me explain with a usecase, so you understand it better -
AsyncTask - Want to get something from the server, or post something to the server? If we do so on the main thread, the user won't be able to interact with the app. So Asynctask is used, and it performs the network activity in a different thread.
Service - Want to manage something in the background? Like get the users' location every 10 minutes or 1 hour, or alert the user when he is crossing a particular area based on the location. The Service makes the app run even when the app is not opened (the user might be doing something else, or the phone is locked, the Service still runs in the background).
Broadcast Receiver - Assume, you are tracking location and storing locally (when the internet is down). Not when the internet is up, you want to send all of them. So you register with the OS, that you want to listen for that specific event, and you get control.
Or when you want the server to know that the device is restarted, then we just have to implement it.
Clear?
A service and its local memory-variables are loaded into memory and is always running
A BroadCast receiver is only garanteed to be in memory and running while processing an event.
A Broadcastreceiver can be removed from memory by the operating system if the memory is low.
"Service" is a component which runs in the background, without interacting with the user. Every developer can create new Services in his application. Services support true multitasking for Android, as they can run in their own process.
"AsyncTask" encapsulates the creation of Threads and Handlers. An AsyncTask is started via the execute() method.the execute() method calls the doInBackground() and the onPostExecute() method.
Mostly main purpose to download something without user interaction.
"Broadcast receiver" is a class which extends BroadcastReceiver and which is registered as a receiver in an Android Application via the AndroidManifest.xml file(or via code).you can register a BroadcastReceiver dynamically via the Context.registerReceiver() method.
The class BroadcastReceiver defines the onReceive() method. Only during this method your BroadcastReceiver object will be valid, afterwards the Android system can recycle the
BroadcastReceiver.

Stop android app from closing

I'm using the BroadcastReceiver to receive SMS messages with my app, and then edit a database based on what the message says. The app works fine when it's open, but If I leave it on for a long period of time and it automatically closes the app will force close when it receives a message (I think the BroadcastReciever is still working, but the rest of the app has closed). IS there any way to keep the app from closing, or resuming it when it receives a text message?
Thanks
If you want the receiver to be persistent you should consider using a Service instead of a standard Activity for your application. BroadcastReceivers that exist in a standard activity are considered to be a foreground service only when processing onReceive as soon as the execution returns the Activity resumes its normal process priority and can be terminated by the system as needed.
From: BroadcastReceiver
Process Lifecycle
A process that is currently executing a BroadcastReceiver (that is, currently running the code in its onReceive(Context, Intent) method) is considered to be a foreground process and will be kept running by the system except under cases of extreme memory pressure.
Once you return from onReceive(), the BroadcastReceiver is no longer active, and its hosting process is only as important as any other application components that are running in it. This is especially important because if that process was only hosting the BroadcastReceiver (a common case for applications that the user has never or not recently interacted with), then upon returning from onReceive() the system will consider its process to be empty and aggressively kill it so that resources are available for other more important processes.
This means that for longer-running operations you will often use a Service in conjunction with a BroadcastReceiver to keep the containing process active for the entire time of your operation.
For more information on creating a service:
Developer Guides
For a detailed discussion about how to create services, read the Services developer guide.

Android Service

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?

Categories

Resources