BluetoothSPPLibrary
BluetoothSPPLibrary copied to clipboard
Library not working from outside UI
Hi,
I came across a limitation of this library when I tried to connect to a BT device from within a Service (or any sort of Android artifact that does not run under the main thread).
The problem is that the AndroidService class (its treads) can't communicate with the AndroidSPP class via the Handler. Messages are simply lost, and I have most proof that's because they run in a different threads (or should I say, different Loopers). Here is the proof:
If you change in BluetoothSPP.java
the line:
private final Handler mHandler = new Handler() {
by
private final Handler mHandler = new Handler(Looper.getMainLooper()) {
Then the library works if you use it from within a Service (or a BroadcastReceiver, I tried both).
I have some concerns about this solution, though: what if I wanted to have two instances of the library running at the same time (and connecting to different BT devices)? Then one's messages would be arriving to the other instance and the other way around... and that's bad. How about creating its own Looper (I don't know how to do that)? Or maybe creating a unique ID per instance and passing it from the SPP to the Service class, and filter the messages based on that ID? It's a bit messy, but it might work.
Please let me know what you think (if you are still alive, of course). I would be very happy to submit a PR if you are happy to accept it.
ouch, now that I think about it... even if I use the same looper, they would be different handlers, right? So messages should not be leaked I believe, but I am not sure. I think it might be quite safe to solve it this way, let me try to submit a PR and take it from there.
Your solution is absolutely right! +1 for you.