Bluetooth connection for Android via RN42 module
I am trying to connect my application to an RN42 module.
// Create a socket based on the application ID with a paired device
// Fetch the published UUIDs from the mbed and use the first one
bluetoothSocket = connectedDevice.createRfcommSocketToServiceRecord(connectedDevice.getUuids()[0].getUuid());
// Connect to the device
if (!bluetoothSocket.isConnected())
bluetoothSocket.connect();
// Create the input and output streams for sending/receiving messages
socketInput = bluetoothSocket.getInputStream();
socketOutput = bluetoothSocket.getOutputStream();
I have this in my android manifest
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
I am getting this error when I call bluetoothSocket.connect()
.
Attempt to invoke virtual method 'void android.bluetooth.BluetoothSocket.connect()' on a null object reference
After calling this line
bluetoothSocket = connectedDevice.createRfcommSocketToServiceRecord(connectedDevice.getUuids()[0].getUuid());
I checked the variable bluetoothSocket
using Android Studio but not null. It somehow becomes null when called bluetoothSocket.connect()
.
Is this the expected behavior? What can I do to fix this? The RN42 module works great as I tested it using the RN Bluetooth Chat app on the Play Store.
I'm on Android 5.1 on a Nexus 7 if that helps.
I managed to solve the problem by removing the bluetooth connection code and relying on an example instead Android Bluetooth Chat
. I don't know what the problem is, but the Bluetooth Chat example managed to fix it. Nothing obvious stands out, so I think it was something subtle. If you have a similar problem and the connection between RN42 and Android is inconvenient, create a sample Bluetooth Chat app and reuse this Bluetooth pairing code.
Many have less headaches! :)
The Seethis Reference Manual for the module (page 21).
This may or may not be relevant to your case, but it is probably worth a try. They have special guidelines (default UUID and custom UUID respectively) for a module when connecting to Android devices.
Use createInsecureRfcommSocketToServiceRecord instead. An insecure socket allows RFCOMM to communicate with an unauthenticated paired device. Embedded devices such as the RN42 or KC2114 have a tricky time to complete authenticated pairing as user interaction is required (digital comparison, yes / no answer). Automatic pairing "Just Works" will not result in authenticated pairing. KC2114 supports both automatic authenticated pairing (with a little hack) and unauthenticated Just Works paired connection.