I am confused about where Android services run. I know services marked 'remote' run in their own processes, but what about ordinary local services?
The reason I ask is I want two local services to cooperate but not be blocked by each other. So for example, Service1 manages a network connection and receives packets. On receipt of a packet, I need that service to hand-off the packet to Service2 that processes the information and takes some action, including possibly sending a return message. I need the receipt, hand-off and processing to happen asynchronously, so the network service can continue to receive packets whilst the application service processes them. How do I ensure this happens?
I know one solution is to broadcast Intents, but how do I include custom data objects (i.e. packets) in an Intent? I don't want to implement the parcelable interface (overkill for local services) but I really need to be able to hand-off complex data objects between the services.
Thanks
Everything in your manifest file that is defined to run in the same process also share the same main thread. This thread is also sometimes the UI thread if that process has activities running in it. So, if you have two local services and they are running in the same process they are going to share the same main executing thread. In order for them to both do work 'at the same time' (until multicore android devices exist all execution is sequential anyway) then your service handling the network connection is going to need to do that in a separate thread. Your other service will need another thread as well.
Your problem is commonly called the producer-consumer pattern. Here's a link quick example of an simple implementation using blocking queues.
Related
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.
I am implementing app that is going to be always running and connected to server.
So the tablet has nothing to do other than running this app, and checking the server all the time for updates to show on the screen.
What can be the best practice to keep the app always running and connected?
In my experience, i have 2 options to solve this problem:
Service always running and connected to my activity to keep it updated.
Keep the work in threads within the activity, since the activity will stay always on. The app will be always on.
My questions are:
What is the best practice for keeping the app running all?
What is the best practice to keep the app connected ? Threads within activity? or service connected to activity?
Is there any preferable structure for such application type?
thank you
Battery is something that i will always take into consideration especially when networking task has to be done. So analyze the point where the is absolute necessary to connect to server.
Whenever you server needs to contact the device use GCM push notification that will save your battery juice which you will spend in polling the server
Well for
Service v/s Thread
is concern the use service in which you should spawn worker threads which will perfrom the networking task
these threads will notify the main service thread when they are done for that you need to user Handlers in android
i will favor service over thread because if you close the activity network request will still be fulfilled once request is complete save it in some storage form(database/share pref/content provider) and retrieve it from them. Once you are done dont for get to destroy the service by all stopSelf a appropriate point or else the service will keep exhausting you phone resource. which will make you app a bad citizen.
A simple implementation of the about pattern i mentioned is IntentService which will automatically spawn the worker thread i.e you just have to override handleIntent method and do all the heavily lifting there which will not be on main thread. And IntentService kills it self when if finds itself doing nothings
The question which you have asked to my understanding is related to syncing with server you can find more about in from android docs
http://developer.android.com/training/building-connectivity.html
If you read the official docu from Android. The best solution is using a service for your kind of app. It's prepared to run continuosly in background. You can implement it to check the network in a transparent way and you can bind the information to another activity. Furthermore, it's more scalable if later you want to change your connection or requirements (it won't affect to your apps activities).
EDIT.
The good point is, that if someday for a reason your app is not in foreground. The service can still be running. Services are prepared for long running tasks http://developer.android.com/guide/components/services.html
My app connects to multiple SPP Bluetooth devices all of which stream data. There are four devices streaming, one at 250 Hz and the rest at 100 Hz. I want to put them in a Service but also want each device to run in a separate Thread. Each Thread must also connect to the SQLite database to insert data in real-time. The devices can connect for long periods and can disconnect at anytime and reconnect at anytime. Once started the app could be running for 24 hours or more and always looking for the availability of already paired devices.
The questions is: is it better performance-wise to do this in a separate Service running multiple Threads (a Thread for each connecting device) or is is better to run a separate IntentService (which will of course runs in its own worker Thread?
I have read many other questions and answers in SO and elsewhere about this and can see the advantages and disadvantages of each approach but I cannot find an answer that specifically answers my question. I am not sure if running multiple Threads in a Service will not still block the main Thread at times. On the other hand I do not think I can run multiple Threads in an IntentService at the same time.
In your intended scenario, IntentService is not a bad idea, but not in the way you are proposing. Based on the documentation:
IntentService is a base class for Services that handle asynchronous
requests (expressed as Intents) on demand. Clients send requests
through startService(Intent) calls; the service is started as needed,
handles each Intent in turn using a worker thread, and stops itself
when it runs out of work.
This "work queue processor" pattern is commonly used to offload tasks
from an application's main thread. The IntentService class exists to
simplify this pattern and take care of the mechanics. To use it,
extend IntentService and implement onHandleIntent(Intent).
IntentService will receive the Intents, launch a worker thread, and
stop the service as appropriate.
All requests are handled on a single worker thread -- they may take as
long as necessary (and will not block the application's main loop),
but only one request will be processed at a time.
So, launching an IntentService for each bluetooth device would mean one or the other would be blocked. Whenever I communicate with multiple sockets (devices), I assign a thread to each socket... this thread is then responsible for connecting to, communicating with, and reconnecting to the socket as necessary. This pattern is the same used in any server program: There's a ClientThread for each connection, which gets spawned by the connection listener.
However, there's a good place for an IntentService as well: It's great to deliver the data to you sqlite database. Place the datum in an intent, send it to your IntentService, and it will open the database (possibly even start a transaction) when it needs to, then post all data, and when it runs out of work, commits the transaction and closes the database. A lot of the necessary plumbing for that is provided by the API.
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/
I am developing an application which utilizes a custom network protocol over TCP. Several tasks within the application use different activities however each activity requires the networking enabled (since each activity has to send/receive some custom packets over the network).
So my idea is basically to
At application start - create a service to handle networking ( I read somewhere that I should do the networking in another thread in this service to prevent ANR)
When a new activity is run, it binds to that service. During that time it sends/receives data from the service. When the activity ends, it unbinds from the service.
I would like to know if this makes sense.
Also, I understand that I can send data to the service (to send over the network) using the aidl interface, but how would I receive data from the service? Polling through the aidl seems to be the only way I can think of - which means I would need another thread in each of my activities to prevent ANR. Surely there is some better way.
I appreciate your help and am open to suggestions.
Actually I've been reading more and am beginning to look at callback methods in the sample code provided here. After reading it more thoroughly I have a better understanding of the services and AIDL.