我在让我的设备在 Android 中配对时遇到问题。如果我进入设置并手动配对它们,我可以使用以下代码让它们连接:
服务器
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.connect);
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(discoverableIntent, REQUEST_ENABLE_BT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == REQUEST_ENABLE_BT)
{
if(resultCode == RESULT_CANCELED)
{
new AlertDialog.Builder(this)
.setTitle(R.string.error)
.setMessage(R.string.bluetooth_unavailable)
.setPositiveButton(android.R.string.ok, AndroidUtils.DismissListener)
.create()
.show();
}
else
{
mServerSocket = mAdapter.listenUsingRfcommWithServiceRecord("Moo Productions Bluetooth Server", mUUID);
mState = State.ACCEPTING;
BluetoothSocket socket = mServerSocket.accept();
mServerSocket.close();
connected(socket);
}
}
}
客户端
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;
}
}
但如果设备尚未配对,它会在没有连接到有效套接字的情况下退出 foreach。在那种情况下,我开始发现。
// 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();
}
}
}
}
但它永远找不到其他设备。我从来没有看到配对对话框,当我一步一步看到它发现了正确的设备,但它无法连接并出现此异常 java.io.IOException: Service discovery failed
。关于我缺少什么的任何想法?
最佳答案
如果服务器实际上不可发现,您的客户端将永远不会发现该服务器。您的服务器代码的评论说“确保设备可发现”,但在套接字上监听并不意味着该设备是可发现的。您可以通过调用使服务器可发现:
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
这是一个 Intent,因为可发现性必须由系统启用,并且只有在获得用户批准后才能启用(因此这将引发一个对话框,请求可发现性 300 秒)。只有在这个 300 秒的窗口中,服务器才能真正被发现。在此期间,您的客户端代码应该可以正常工作,您将收到配对请求。
Android 开发指南中对此进行了详细介绍: http://developer.android.com/guide/topics/wireless/bluetooth.html
关于安卓蓝牙配对失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2437664/