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.
Related
I know this look like tons of question around SO. But it's not (although I can also be wrong).
I have a long running Service (running in a separate thread using blutooth socket pooling for data in a OBD2 adapter every 5 seconds).
This Service is running in the same process and is a Foreground Service.
The user start this Service through an Activity. It then connect to the Bluetooth device and start pooling and saving data to a SQLiteDataBase.
The user can then minimize the activity and do other stuff.
When he returns (if ever, he can stop the service through a notification area button) to the application it checks if the Service is running and if so, it starts another Activity which show the data that is being pulled from the OBD2.
My question is, between this visualization Activity and the Service should I use and by this I mean the recommended or the right one:
LocalBroadcast? This is actually what I am using. Every time the service pull some data, it sends a broadcast with the data everytime it was pulled. Then in the onReceive method call runOnUiThread to update the respective View.
Messenger? As far as I know (never used it) I should send a Messenger from the Activity to the Service (much like a Handler) and in the Service it should send the Messages with the data pulled. But from this I would get a RemoteObjectException if the Activity was destroyed (like I said, the user could just minimized the activity and then it got GCed). So, I would probably need a way of sending the Messenger to the Service every time the Activity gets created and check if it's ok to use the messenger form the Service every time (if that's even possible, I've never used this).
BindService? Should I bind to the service when I open the Activity and then get the data directly from methods in the Service? But this would probably mean I would have another thread in the Activity gets this data from the Service every time, right?
Handler? (for a moment now I realize don't know the difference between Messenger and Handler, should it be that "use Messenger when Service runs in another process and Handler otherwise)
I've seen/read a lot of answers here in SO and through the web in general.
But in the end I don't see a ultimate answer for my case. But I'm sorry if this is just because I couldn't figure it out.
Thanks in advance!
EDIT: forgot to mention, I would rather make use only support libraries and android framework stuff, I'm still learning Android and I want to understand what's happening within its own classes.
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
I started learning android i've been playing with it and so far so good but i have some doubts about Services, i started learning them today so by gently if a say something very wrong.
For example, i want my app to grab some information over the internet from time to time, this polling period is defined by the user, then the UI gets updated. I though about creating a Service that run lets says every 30 minutes, gets the information and updates the UI.
If i get it right:
An IntentService just executes an operation and stops by itself sending the result through an intent(right?), so i think it's not what i want.
A Bounded Service is most likely used when you want IPC or allow binding from external apps, which again i think it's not what i want.
I think a Local Service is probably what i need, using a LocalBroadcastReceiver to update the UI, how can i make it to run the operation every X minutes( Handler postDelayed, ScheduledExecutorService or Alarm Manager ? )
If i understand it right a Service if not bounded can run infinitely if it's not killed due to low memory problems, making it a foreground Service is the safest ?
Last thing and it's kind of a noob doubt, if the user leaves the application(Click Home Button or opens other app) the app is still in background but the activities are in "Paused" or "Stopped" mode will the Service still be able to talk to them ?
Sorry for long post and thank you.
Your requirement : after every x minutes, start a service, pull some date, update UI.
Solution :
Define or set an alarm for every x minutes, to trigger a receiver.
From receiver start the service.
In the service, start an async task to fetch the data in doInBackGround().
Once data is fetched, from onPostExecute() send a broadcast to your activity.
In the activity have a dynamic receiver registered for broadcast sent from service.
From dynamic broadcast receiver update UI.
From what you've explained I wouldn't personally use a service.
The Android docs on services explain more but here is a snippet:
http://developer.android.com/guide/components/services.html
A Service is an application component that can perform long-running operations in the background and does not provide a user interface.
You could perhaps looks at using an AsyncTask, especially given that you only want it to run whilst the app is running:
http://developer.android.com/reference/android/os/AsyncTask.html
This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
There is a good answer here on how to run an AsyncTask repeatedly at specific time intervals: How to execute Async task repeatedly after fixed time intervals
I know how to implement a BroadcastReceiver that is notified a new outgoing call is starting.
I also know how to eventually drop the call and handle it within the application.
What I'd like to know is if it is reliable to ask the user whether to drop it or not?
As far as I know the application has a limited amount of time to return from the RroadcastReceiver.
How long is this time?
Have you ever implemented it?
EDIT
Trying implementing it I realize that there is a bigger problem. In a BroadcastReceiver you can't show a dialog. Form the doc:
In particular, you may not show a dialog or bind to a service from
within a BroadcastReceiver. For the former, you should instead use the
NotificationManager API. For the latter, you can use
Context.startService() to send a command to the service.
The reason is that you can't perform AsyncTask. I thought I was going to use signals to implement it but you can't do it because the broadcast-receiver is started in the main thread and you can't make it waiting...
Is this right?
As far as I know the application has a limited amount of time to return from the BroadcastReceiver. How long is this time?
Formally this time is about 5 seconds - after 5 sec. while system main thread can't process system messages Android should throw ANR (Application Not Responding) dialog and force close your application.
More generaly - BroadcastReceiver onReceive() method should finish as soon as possible.
If you want show some UI elemets to the user, I think you should start your own Activity for that purpose.
I am working on a small project. We need to do the following:
Have a background service/whatever running on your android ph which
listens for a sms with some specific content in the msg body
On encountering that specific content, make a webservice call to a
remote server to download some event data
Set the fetched event data as reminders in the calendar
All the above must be done without any user interaction.
I have managed to do #1 via a broadcast receiver. Didn't need to run a service for it.
For #2, I plan to call the web service via the Broadcast receivers onReceive() method and get the data. Once I have the data, how do I go about setting the same so that the user gets his/her timely reminders based on the same? There is no activity opening up or anything that the user can see. He should just get the reminders (even if he restarts the ph).
Any help will be much appreciated. Thanks!
For #2, I plan to call the web service via the Broadcast receivers onReceive() method and get the data.
Please don't. This will be unreliable and will freeze your UI if you happen to have the foreground activity. onReceive() is called on the main application thread, and Android will terminate your code if it thinks you are spending too much time on that thread, even in the background. Please delegate this work to an IntentService, which has a background thread and automatically shuts down when there is no more work to be done.
Once I have the data, how do I go about setting the same so that the user gets his/her timely reminders based on the same?
On Ice Cream Sandwich (Android 4.0), you could add events to their calendar.
Before that, roll your own reminder mechanism using AlarmManager.
There is no activity opening up or anything that the user can see.
You have no choice but to supply an activity. Otherwise, your app will never run on Android 3.1+. They will need to run your activity once to enable your app, then again every time after they elect to kill off your app via a task killer or the Settings application.