在代码中使用BluetoothDevice.createBond()方法在设备之间进行配对。该方法将返回一个布尔值,表示配对是否成功。随后,使用BluetoothSocket.connect()方法建立连接。
以下是一个简单的示例代码:
private BluetoothDevice device;
private BluetoothSocket socket;
...
// 为设备创建一个蓝牙套接字
socket = device.createRfcommSocketToServiceRecord(MY_UUID);
// 开始配对
device.createBond();
// 等待配对完成
while(device.getBondState() != BluetoothDevice.BOND_BONDED){
// 等待...
}
// 连接蓝牙设备
socket.connect();
请注意,您还需要在AndroidManifest.xml文件中添加BLUETOOTH和BLUETOOTH_ADMIN权限。
上一篇:Bluetooth外设无法配对。