IntentService, Service, or AsyncTask - android

What would be the best way to implement this. I have an Android app that will use my python server to allow communication between 2 phones in rounds. Rounds mean that they can't talk to each other until a round start and once they send a message they can't send another until the other person responds which will then start a new round.
I was thinking I would use the IntentService but it seems wrong to have the server constantly starting and stopping and I don't won't to have to worry about the issues with asynctask or is that the best way to handle it. How could I have a service that should receive and send messages to the client, seems services are more one way things?

Intent services are nothing more that worker threads that are triggered by intents, execute their actions in a separate thread and then get shut down. They are designed to be started and stopped.
If you need to perform stuff like an http get, or in any case interaction that do not require to stay connected to the server, use intent services and get your activities notified using broadcast events.
If your app needs to stay connected with the server (i.e. permanent tcp connection), the way I'd go for is to have a service (not an intent one) that performs the networking stuff using an asynctask or a more classic thread hosted in the service. You can then make the activity interact with the service using bindToService() .
I'd recommend not to use asynctasks inside an activity. You will risk to loose the server response in case of horizontal / vertical view changes, as oneilse14 stated in his reply.

I highly recommend the IntentService/Broadcast Receiver route. Avoiding the nasty configuration change issues associated with AsyncTask will make your life ten times easier.

As far as i understood your problem is of type worker-queue model Producer-consumer model). Intentservices are meant to do that. You should use services if and only you need to do multithreading. You do can communicate with Activity and Service by using IBinder interface.
Asynctask are just a specialized threads so that you can update your UI easily. But for your case IntentService seems to be best option.

I would use an Alarm, which is scheduled via the AlarmManager, as then it can be set to check if the round has started/turn. It has the advantages of a service but not the horrors of battery drain. It takes a frequency to how often the Alarm should run, which even includes enumerations of time (e.g. 1 hour/day/week).
When the Alarm runs it could poll to see what the current state is and react accordingly. For example a notification could go into the status bar and phone could make an audible noise and vibrate.The benefit of this is that the user does not have to keep the app running as the Alarm will trigger a broadcast receiver.
An example of the Alarm code: http://www.androidcompetencycenter.com/2009/02/android-basics-alarm-service/

Related

An Android Service constantly performing some different jobs depending on each other

I want to constantly, without stopping, perform 2-3 kinds of operations from my Service in Android. That is:
check if some hardware is connected and retrieve the data from it every 1 second and save it to the files
send those files a server
perform some calculations
The second job depends on the 1st one.
Note that the Service will have GUI as well if that matters, but the GUI will be used rarely. Most of them time the Service will work in "background" doing what it has to do.
How can I do that? Should there be 3 different threads or what? Or I don't need the thread because it'll be a service?
Any help is appreciated.
If you want to perform all operation in parallel in background then use android service and use ScheduledThreadPoolExecutor class to achieve this.
Otherwise use timer or Executor(with onr thread) inside android service to perform all operation in serial manner.
Let me know, This is helpful for you?
That depends on what type of service you are using, Intent Service or Service.
If you are using Intent Service, then you don't have to worry about creating a new thread, as it itself creates a worker thread.But, just keep in mind that, it takes one care of requests one at a time, in queue manner and stops itself when the processing is done.
But if you want to perform simultaneous request at once, extend from Service. You will have create a worker thread to run this service as it doesn't create a separate thread.
Check developer guide for more info:
https://developer.android.com/guide/components/services.html
To communicate between two services, you have to make use of Broadcast Receiver to receive intents which you can send from your first service or use listener callback, but i would suggest you to use Broadcast Receiver and intents.

In Android when collecting data using a sensor should I use IntentService or Service?

I'm making an app that will collect data using a sensor, only when the device is on. This program will mainly run from the notification bar. Most of the posts about using sensors in the background seem to suggest using Service but I've read that IntentServices are the way to go if handling a long task. So I was wondering which one would be best to use?
It sounds more like you would need a Service, as you will have a long-running operation (monitoring the sensors) which will pause (but not destroy) during some periods when the monitoring will not be required.
Using a Service will also allow your app's activities to bind to it, and show something like live updates. What you however need to be aware of is that if you would like to do something periodic in your Service then you will need to handle the scheduling and threading (if necessary, depending on the amount of processing required) yourself.
You could for example use an IntentService if you wanted to send the collected data to a remote server, as this will nicely kick off a worker thread for you to perform the (slow) network request on.

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.

Design approach to use in Android when several activities need to connect to a service

I have a class that starts a Bluetooth reading thread and another that receives/decodes what's read from that port and produces some output logs depending on the information read.
In my design, those 2 components form a service for my application (multiple activities) from where I would like to start/stop getting the output logs on a continuous basis (typical frequency of 2-3 logs per second).
My questions:
1) Should I derive from Service or IntentService. The doc says about IntentService: "This is the best option if you don't require that your service handle multiple requests simultaneously". This may be my case since the main activity will start/stop the service...
2) What would be the appropriate way to catch the service events? Does the BroadcastReceiver is appropriate for this type of communication?
3) I may need to occasionally send some stuff to the Bluetooth port. So, I'll have to pass information from my application to the service. Does the PendingIntent should be used for that?
Thank you!
Should I derive from Service or IntentService
IntentService is designed for discrete tasks, not stuff that would run indefinitely until the user manually stops it. I would use Service.
What would be the appropriate way to catch the service events? Does the BroadcastReceiver is appropriate for this type of communication?
That is certainly one approach. You might use the LocalBroadcastManager from the Android Support package to reduce overhead and keep everything private to your app. Have your activities register a receiver in onResume() and remove it in onPause(). The foreground activity will then be notified of events.
I may need to occasionally send some stuff to the Bluetooth port. So, I'll have to pass information from my application to the service. Does the PendingIntent should be used for that?
No, I would have the activity simply send a command to the service via startService(), with the data to be passed included in extras on the Intent. If you have data that cannot be packaged as extras, you may need to consider binding to the service, so you can get a richer API, though this makes configuration changes more annoying.

What to use: service or threads

I am developing an android app which fetches/uploads data from/to the web service every n minutes. This upload/download is only done when the app is running. But this might change in future.
I dont update the UI when the new data is downloaded. The UI is only updated if the user is on the current screen(app have multiple activities)
My question is what is the best approach to this problem.
I dont think service is the right approach as it sounds like an overkill(in the present scenario). AlarmManager could be an option.
Running threads inside a service be an option ..something like this .
Any pointers/suggestions would be great.
Thanks
I am using AsyncTask in my activity to ask .net web service some information and it works and easy to use.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
Well, in this case, since the app would already be running during the time, either would work great, but a service can be called from anywhere within the application so this is where I would use the service over the thread.
If you want to create the thread to only be used in lets say Main.java, then thread would work fine, these are the only things that I can see really making ANY difference at all, they're really pretty close, and in this case neither gives a distinct "correct" answer, but I would choose Service
I think all approaches you noted would work ok. Personally I'd go with this:
Use AlarmManager to wake download service. Start it when Activity is shown, stop it when activity hidden.
Download service should be short lived: start it to do the upload/download and then shut it down.
If download service does get some new data, it sends a Broadcast which Activity listens to.
Just broadcast a message after your upload/download is done, and then have a receiver start the service and then have that service stop itself. And you are done.
This should be done if you dont plan on polling the server for new information or anything. Primarily this kind of approach would be for onetime update, interpret, finish. And wait until the next update. Which primarily for most cases is streaming.. but depends on what you are getting.

Categories

Resources