Android蓝牙套接字连接耗时太长,最终失败

Wes*_*ley 5 android bluetooth

我正在尝试从Android手机连接蓝牙设备.在大多数情况下,连接成功.我使用以下代码进行套接字连接:

        if (isUsingHtcTypeConnectionScheme) {
            try { 
                if (LOG_ENABLED) Log.d(TAG,"connecting to SPP with createRfcommSocket");
                Method m = mRemoteDevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
                tmpSocket = (BluetoothSocket)m.invoke(mRemoteDevice, 1); // may be from 1 to 3
            } catch (java.lang.NoSuchMethodException e){
                Log.e(TAG, "java.lang.NoSuchMethodException!!!", e);
            } catch ( java.lang.IllegalAccessException e ){
                Log.e(TAG, "java.lang.IllegalAccessException!!!", e);
            } catch ( java.lang.reflect.InvocationTargetException e ){
                Log.e(TAG, "java.lang.InvocationTargetException!!!", e);
            }
        }

        if (tmpSocket == null) {
            try {
                if (LOG_ENABLED) Log.d(TAG,"connecting to SPP with createRfcommSocketToServiceRecord");
                tmpSocket = mRemoteDevice.createRfcommSocketToServiceRecord(uuid); // Get a BluetoothSocket for a connection with the given BluetoothDevice
            } catch (IOException e) {
                Log.e(TAG, "socket create failed", e);
            }
        }

        mBtSocket = tmpSocket;

        try {
            mBtSocket.connect();
        } catch (IOException e) {
            connectionFailed();
            setState(STATE_IDLE);
            return;
        }
Run Code Online (Sandbox Code Playgroud)

如果其他设备的蓝牙未打开,它将在2-3秒内抛出IOException,这是正常行为.

但有时连接需要20-30秒并最终失败,而其他设备的蓝牙功能已打开.

我想知道为什么会发生这种情况,如果手机无法连接到设备,它应该在2-3秒内抛出IOException.但现在需要20-30秒才能抛出IOException.(其他设备已准备好连接)

我在几部Android手机上测试过也有这个问题,所以可能与特定手机无关.

有任何想法吗?谢谢!