我是android和java的新手所以要温柔:) 我正试图通过bloototh连接两部手机。 我正在制作两部手机,通过创建serversocket来监听来电,然后从一部手机(作为客户端)初始化连接。有趣的是,当我试图让我的LG(Android版本2.3.4)连接HTC(Android 2.2.1)一切正常,但当我尝试使HTC手机连接作为客户端我没有得到任何结果。调试器显示HTC在mmSocket.connect()时失败;并执行catch(IOException connectException)。我的代码基本上是从android蓝牙教程复制/粘贴。有什么建议为什么手机的行为不同?连线:
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
BtAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect(); **HTC phones fails here and goes to CATCH block**
// make info message
Message msg = mainHandler.obtainMessage();
Bundle bundle = new Bundle();
String btnTxt = "Connected";
bundle.putString("myKey", btnTxt);
msg.setData(bundle);
mainHandler.sendMessage(msg);
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
ConnectedThread conThread = new ConnectedThread(mmSocket);
conThread.start();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
答案 0 :(得分:0)
可能存在问题
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
在您的HTC 2.21设备上。检查HTC设备的Bluetoth适配器支持哪些功能,这可能与您的程序失败有关。
“仅当可以使用经过身份验证的套接字链接时才使用此套接字。 身份验证是指要防止的链接密钥的身份验证 中间人类型的攻击。例如,对于蓝牙2.1 设备,如果任何设备没有输入和输出 功能或只是能够显示数字键,一个安全 套接字连接是不可能的。在这种情况下,请使用{#link createInsecureRfcommSocketToServiceRecord}。有关更多详细信息,请参阅 蓝牙核心规范的安全模型部分5.2(第3卷) 版本2.1 + EDR。“