研究android蓝牙连接时,在网上找了个例子,作为客户端在调用connect函数时失败。经查资料
将
socket = device.createRfcommSocketToServiceRecord(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666"));
改为
Method m;
try {
m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
try {
socket = (BluetoothSocket) m.invoke(device, 1);
_bluetooth.cancelDiscovery();
try {
socket.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
就可以连接。
===========================================================
注释: 实际上tmp = (BluetoothSocket)m.invoke(device,Integer.valueof(可以使用的端口号));这个命令的参数意义。另外实际上第一种socket创建方法是错误的,第2种才是正确的。