0

我对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) { }
    }
}
4

1 回答 1

0

可能有问题

tmp = device.createRfcommSocketToServiceRecord(MY_UUID);

在您的 HTC 2.21 设备上。检查 HTC 设备的蓝牙适配器支持哪些功能,这可能与您的程序失败的原因有关。

“仅当经过身份验证的套接字链接可能时才使用此套接字。身份验证是指对链接密钥进行身份验证以防止中间人类型的攻击。例如,对于蓝牙 2.1 设备,如果任何设备不具有输入输出能力或仅具有显示数字键的能力,安全套接字连接是不可能的。在这种情况下,使用 {#link createInsecureRfcommSocketToServiceRecord}。有关详细信息,请参阅安全模型第 5.2 节(vol 3) 蓝牙核心规范版本 2.1 + EDR。”

http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createRfcommSocketToServiceRecord%28java.util.UUID%29

于 2013-06-18T21:43:53.063 回答