0

I am working on an Android application which relays data from a socket connection to a Bluetooth interface. For comfortably communicating I have instantiated two BufferedReaders which I want to listen to simultaneously in an IntentService. Furthermore, I want the service to be able to react to events such as a Bluetooth or WiFi connection loss. However, the service should run until a specific exit command is received on the server interface.

So far, I use two threads, but I can't figure out how to comply with my requirements.

SOLUTION

The solution is to use a regular Service instead of an IntentService. In the service I use two asynchronous methods which are AsyncTasks in my case for connecting to the Bluetooth device and to the server. Once the connections are established I start two threads listening for data using the blocking readLine() method. In the service I simply do nothing which keeps the main thread free for handling Bluetooth connection loses. The service is terminated by my activity once the user wishes to disconnect.

Lukas
  • 756
  • 7
  • 20

1 Answers1

1

Don't use an IntentService to handle this, but rather your own Service derived implementation. IntentService is design to handle incoming Intent objects on a temporary background thread then completely shutdown once all Intents have been handled. You're already moving most of the heavy lifting off into your own background threads, so there's no need to use an IntentService. However, be sure that any onStartCommand() implementation you create does not do blocking operations since that is executed on the main thread.

Larry Schiefer
  • 15,687
  • 2
  • 27
  • 33
  • I plan to use two services, one for the Bluetooth connection and one for the socket connection. For relaying data between these two (for example data received on the server side should be sent to the Bluetooth device) should I use regular `Service`s or bound ones. – Lukas Mar 15 '16 at 14:16
  • You can actually just use the same `Service` and the two different threads you already have setup. The only reason to explore bound services is if they are running in different processes (apps) or you intend to make them run in separate processes in the future. – Larry Schiefer Mar 15 '16 at 14:18