3

我正在编写一个基于 android 蓝牙聊天示例的蓝牙游戏。我有两部手机要测试。这是问题,当我将一部手机连接到另一部手机时,它有时会显示“无法连接设备”捆绑包,但是当我运行蓝牙聊天示例时,它从未显示过这个,所以我认为这不是设备的问题. 有没有人研究过蓝牙聊天示例并且有同样的问题可以给我一些帮助?

我尝试打印异常,就像“java.io.IOException:服务发现失败”。这是导致异常的代码。

private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        mmDevice = device;
        BluetoothSocket tmp = null;

        // Get a BluetoothSocket for a connection with the
        // given BluetoothDevice
        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            Log.e(TAG, "create() failed", e);
        }
        mmSocket = tmp;
    }

    public void run() {
        Log.i(TAG, "BEGIN mConnectThread");
        setName("ConnectThread");

        // Always cancel discovery because it will slow down a connection
        mAdapter.cancelDiscovery();

        // Make a connection to the BluetoothSocket
        try {
            // This is a blocking call and will only return on a
            // successful connection or an exception
            mmSocket.connect();
        } catch (IOException e) {
            Log.e("error", e.toString());
            connectionFailed();
            // Close the socket
            try {
                mmSocket.close();
            } catch (IOException e2) {
                Log.e(TAG, "unable to close() socket during connection failure", e2);
            }
            // Start the service over to restart listening mode
            BluetoothChatService.this.start();
            return;
        }

        // Reset the ConnectThread because we're done
        synchronized (BluetoothChatService.this) {
            mConnectThread = null;
        }

        // Start the connected thread
        connected(mmSocket, mmDevice);
    }

    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "close() of connect socket failed", e);
        }
    }
} 

确切的位置是
mmSocket.connect();

4

1 回答 1

2

我知道你会觉得答案很奇怪,说实话我不太擅长 UUID。但是我遇到了同样的问题并使用它解决了它。

回答
我认为您使用的是在BluetoothChat应用程序中硬编码的 UUID。当我将这些 UUID 更改为众所周知的 UUID 时,即;“00001105-0000-1000-8000-00805F9B34FB”它解决了我的问题,但我不再明白了IOException--Service Discovery Failed

所以,我建议你改变:

从:

private static final UUID MY_UUID_SECURE =
    UUID.fromString("ea87c0d0-afac-11de-8a39-0800200c9a66");
private static final UUID MY_UUID_INSECURE =
    UUID.fromString("7ce255c0-200a-11e0-ac64-0800200c9a66");


private static final UUID MY_UUID_SECURE = 
    UUID.fromString("00001105-0000-1000-8000-00805F9B34FB");
private static final UUID MY_UUID_INSECURE = 
    UUID.fromString("00001105-0000-1000-8000-00805F9B34FB");

此答案的来源。

于 2013-10-05T06:40:47.287 回答