Bluetooth RFCOMM connection couldn't be established consecutively on Android 4.2
android, bluetooth, rfcomm
Solution
I have finally figured out the solution.
It turns out that it's not a bug in the new Bluetooth driver. It's a corner case not considered in Bluetooth sample application, more specifically, BluetoothChat project, provided by Android SDK.
In the Bluetooth service code inside BluetoothChat sample project, when connection is failed or lost, it always starts the service over to restart listening mode. It's no problem when the phone is used as server, however, in some scenarios when the phone is used as client, once it goes into listening mode, you can't connect to other servers. Because in "connect" function, it doesn't cancel (In)SecureAcceptThread. So essentially you are listening to other connections as server while trying to connect to other servers as client. It's conflicting.
The way to solve this issue is, if you are sure your phone will not be used as server listening to incoming connection, then simply remove the code to restart listening mode once connection is failed or stopped.
Problem
I have an application which talks to a custom device through RFCOMM via Bluetooth. The communication code is based on BluetoothTalk sample project. It was running without any problem before on either Galaxy S3, Galaxy S2, Galaxy Note and Nexus 7. Recently, Nexus 7 were upgraded to Android 4.2 and since then, the problem happens as follows: When you use the app to set up a connection for the first time, meaning that the device is just turned on and app is just launched, no problem, you can get data normally. Then if you stop the communication, and try to restart, the communication fails with error "java.io.IOException: bt socket closed, read return: -1". From then on, no matter how many times you try to reconnect, it simply always fails. The only way to make it work again is, if you reboot the custom device AND the app, then try to connect, the communication becomes normal. But then, once you stop and restart the communication, it keeps on failing. I borrowed a Nexus 4 with Android 4.2 and the issue remains. It's really annoying because the main value of our device is relying upon the Bluetooth RFCOMM application. I double checked about the documentation on BT in Android 4.2 and didn't see any significant change. I'm fairly confident about the code on my side because it works for any Android device not running 4.2 Any hint or suggestion would be greatly appreciated. The device need to be demoed in the very beginning of December and we really want to address this issue ASAP. EDIT: Now that 4.2.1 has been released and the problem is still not solved. Can we at least get some confirmation regarding if it's under working and will be fixed soon?