Bluetooth Communication in thread or Service in Android? - android

I am developing app which has bluetooth communication involved. The bluetooth communication should go on even if the Activity that sets up the connection closes down. First, I have thought of using Service for this and that seemed to be right way. But, in Bluetooth chat example the communication happens in another thread and not in Service. I have used that code in my app and its working properly. Is using Thread for bluetooth communication proper or do I need to make use of Service only? The bluetooth communication should be active till my app is in RAM and it should not matter if I switch between activities.

Well a seperated Thread is not differnd then a service in you case, except that it follows the activity life cycle of Android, but a Thread might be killed and no state can be recovered. Android will try to restarted a service once it was killed.

A little too late to answer your query, but better late than never I suppose.
I have worked on an application that has the bluetooth communication between two devices and I would like to summarize my experience.
A service we use normally when we want do some background process that is not very heavy, in a way, I mean the service (if it is huge) will block my main UI thread hence slowing down your OS or ANR may be, which is what we don't want.
The bluetooth communcation is an ever running process which should be done using a Thread only as this will work as a separate thread and wont have any impact on the main UI thread.
Please correct me if I am wrong.

Related

What is the best practice for always running networking android app?

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

Android application design: Right split between activities, services and threads?

I'm currently trying to finish the design of a larger app which is used for remote controlling wireless devices via a proprietary wireless bridge, a USB host device using CDC.
But right now I'm stuck in how to make the correct split between Activities, Services / IntentServices and worker threads.....
The application will be made of these fundamentals:
- Various GUI screens which offcourse will all be Activities. I intend to have some threads for receiving a few messages and updating the GUI accordingly via handlers upon these message receptions. - any comments on that approach?
A module handling all low level USB/CDC communiation, message serialization/deserialization and message dispathing to the application via queues. This calls for a seperate thread. I don't want this thread to be destroyed just because the activity that spawned it goes away - which in my book calls for an IntentService - right?
Some sequence players which will control the wireless devices in a timed manner. These will be triggered from one my activities and MUST run to the end without stopping due to home button presses, launch of other activities etc. - Again this calls for a IntentService.....right?
A status module updating some "global" data structures (possibly a database) upon message reception from the low level module. Here I am puzzled...coulmd this just be a working thread in my main Activity - or am I looking at a third IntentService?
Would it be better to include all in one service and then just add threads where needed?
Sorry for my noobiness - Android is hard for C++ programmers who have been programming non GUI backgroud tasks for the last century.
Thanks in advance!!!
For bullets one and two you are right that a service is the best approach. An IntentService in particular is good to handle jobs one by one that were sent from somewhere else.
If your service should only keep a particular thread alive which does the message/queue handling on its own (as I understand bullet one), a normal service may be enough.
For bullet three it depends if those updates must be done while your app is not visibly active to the user. If so, use a service as well.
By the way: A thread is not bound to a particular activity or service but to a process. If this process contains a running service then all threads in it are kept alive as well (except the process must be killed due to special circumstances).

Using Service for long network connection

Right now I have a server running on a desktop. I want to be able to start up my app, hit a button to start collecting data from this server, and only stop once I hit to button again. The user should always be grabbing data from this server after hitting the button, even if the app isn't active. So far I've considered setting up a Service or using Threads by themself.
A Service sounds exactly like what I need, but I've been told it isn't meant to sustain a long network connection. I poked through the BluetoothChat sample application and it didn't use a Service. Would a Service be the right thing to use then, or should I implement it with threads like the sample application does? The only reason I need a long connection is to listen for any error reports from the server. The other network stuff only happens when the user is directly using the app. I will have to use threads anyways because a Service runs in the same thread as the activity that calls it, but I guess my main question is whether I should scrap the Service part. Right now I have a basic Service set up that can handle messages sent to it and it seems really easy to use. The documentation on it is just all over the place, there needs to be a section saying "If you want to do X, then this is suggested!"
A Service runs on the UI thread, but an IntentService runs in its own thread.
It's ambiguous to say that the "app" isn't active. If you're running a Service, it's always active. An IntentService is active as long as it has finished the work in its onHandleIntent() method. None of the activities of the app may be active, which means that the app is in the background.
Other than that, I'd need to know more about what you're trying to do. In general, it's better to collect data in cycles rather than trying to keep the connection open constantly. For example, what do you do when the device loses connection to the Internet?

Android Design : How to run 3 different threads in Background for monitoring 3 different devices

I have an application, where I want to monitor 3 Bluetooth devices for their status from the Android Phone. For this, I need to send some data to each device and check if their response is correct every 5 seconds. And I want this processing to happen even when the application is not in Foreground. I thought of different solutions But I could not come up with any good solution.
I thought of using IntentService. But IntentService uses one thread for doing all the processing. But I would like 3 different threads because 5 seconds between every check is low that I cannot hop between checking devices in a single thread.
I thought of using 3 different IntentServices. But Not sure, if its the best way to go ?
I thought of using a Service and spawning of 3 threads, one foreach device. But I was not sure if these threads will run when the app is not in foreground.
What would be the best design to run this sort of app which does background processing in a app even when the app is not in Foreground and it has to run 3 different threads.
One Service, three Threads is what you want. Having a single thread performing I/O on multiple devices just seems like asking for problems, its creating a dependencies that are unnecessary. All Threads execute, regardless of whether the app is foreground or background.
The Android framework doesn't have any way to stop a Thread from running. Thread execution is managed by Dalvik. The framework stops delivering events to an app's main Thread when its in the background (other than events like BroadcastIntents), but it doesn't tell Dalvik to pause all threads in that process. This would kind of defeat the purpose of background processing if it did.
You don't necessarily need three threads. You definitely need three BluetoothSocket s. You might be able to pull it off just by having one Service that starts a thread from onStartCommand() and kills it in onDestroy(). The thread should loop and check if there is an active connection to each device, and if there isn't one, it should attempt to reconnect. Once a connection is established, it should write to and then read from the device, according to its protocol. There is nothing stopping you from writing/reading to multiple devices in the same thread. You can use nonblocking IO for this, checking whether there are bytes to read on each iteration until you find them, and then taking an action based on what you receive.
As far as pairing/bonding goes, I would do that outside of the thread that checks the devices, as you might want to direct the user to enter the pin/pair the device. Just make the background thread read/write to each of the three devices. You may find that you want multiple threads, it's purely a matter of taste... Only one thread is needed.

Android background work scenario

This is the scenario:
User has a main activity used for UI.
Program needs to communicate with peers and keep connection and wait for messages
When a message comes it is shown in the main activity.
So the question is should I use a service for the communication and what type of service?
And also should I use AsyncTask in the service in order to keep my UI responcive and why?
The important thing here is that any CPU intensive work or blocking I/O (including waiting for incoming network connections) occurs in a thread separate from your main UI thread.
If you just need network communication to stay running while your activity is alive, then use a second thread within your activity. If you need to maintain network communication even after your activity has been killed, you'll need to use a service.
Keep in mind that default behavior is for a service to share the same process and thread as anything else in the same application (including the activity that provides your UI). For this reason, even if you use a service, you'll still need to spawn a new thread to get the desired effect.
AsyncTask is used to perform a task in a separate thread that will eventually terminate and return a result. If this sounds like your application, then feel free to use it. But if you're keeping a port open across several requests (meaning you don't have a single return value), using this class would just be a burden.

Categories

Resources