I am having a problem getting my devices to pair in Android. If I go into the settings and pair them manually I can get them to connect using the following code:
Server
// Make sure the device it discoverable
mServerSocket = mAdapter.listenUsingRfcommWithServiceRecord("Moo Productions Bluetooth Server", mUUID);
mState = State.ACCEPTING;
BluetoothSocket socket = mServerSocket.accept();
mServerSocket.close();
connected(socket);
Client
Set<BluetoothDevice> pairedDevices = mAdapter.getBondedDevices();
BluetoothSocket socket = null;
// Search the list of paired devices for the right one
for(BluetoothDevice device : pairedDevices)
{
try
{
mState = State.SEARCHING;
socket = device.createRfcommSocketToServiceRecord(mUUID);
mState = State.CONNECTING;
socket.connect();
connected(socket);
break;
}
catch (IOException e)
{
socket = null;
continue;
}
}
But if the devices hadn't already been paired it gets out of the foreach without connecting to a valid socket. In that case I start discovering.
// If that didn't work, discover
if(socket == null)
{
mState = State.SEARCHING;
mReceiver = new SocketReceiver();
mContext.registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
mAdapter.startDiscovery();
}
// ... Later ...
private class SocketReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
if(BluetoothDevice.ACTION_FOUND.equals(intent.getAction()))
{
try
{
// Get the device and try to open a socket
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(mUUID);
mState = State.CONNECTING;
socket.connect();
// This is our boy, so stop looking
mAdapter.cancelDiscovery();
mContext.unregisterReceiver(mReceiver);
connected(socket);
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
But it will never find the other device. I never get a pairing dialog and when I step through I see that it discovers the correct device, but it fails to connect with this exception java.io.IOException: Service discovery failed. Any ideas as to what I'm missing?