在我的应用程序中,我需要配对蓝牙设备并立即连接它。
我有以下函数来配对设备:
public boolean createBond(BluetoothDevice btDevice)
{
try {
Log.d("pairDevice()", "Start Pairing...");
Method m = btDevice.getClass().getMethod("createBond", (Class[]) null);
Boolean returnValue = (Boolean) m.invoke(btDevice, (Object[]) null);
Log.d("pairDevice()", "Pairing finished.");
return returnValue;
} catch (Exception e) {
Log.e("pairDevice()", e.getMessage());
}
return false;
}
我使用它的方式如下:
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
//Connect with device
}
}
它向我显示对话框以配对设备并输入密码。
问题在于createBond函数总是返回true,并且它不等待我输入密码并与设备配对,因此我无法正确使用:
isBonded = createBond(bdDevice);
if(isBonded) {...}
所以问题是如何与设备配对,当它配对后如何连接?
附注:我的代码基于以下线程的第一个答案:Android + Pair devices via bluetooth programmatically
BluetoothDevice device = adapter.getRemoteDevice(mac);
final UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
out = socket.getOutputStream();
in = socket.getInputStream();
其中adapter
是BluetoothAdapter
的一个实例,mac
是一个字符串。 - RdlPsocket.connect();
。 - RdlP