2012-03-01 148 views
4

我遇到了一个问题,当我调用sock.connect()时,它只是无限期地挂起。没有例外,也没有超时。Android蓝牙套接字连接挂起

try 
    { 
     Method m = dev.getClass().getMethod("createRfcommSocket", new  Class[] {int.class});   
     sock = (BluetoothSocket) m.invoke(dev, 1); 
     sock.connect(); 
     Thread.sleep(100); 
     in = sock.getInputStream(); 
     out = sock.getOutputStream(); 
    } 
    catch(ConnectTimeoutException ex) 
    { 
     return false; 
    } 
    catch(IOException ex) 
    { 
     return false; 
    } 
    catch(Exception ex) 
    { 
     return false; 
    } 

原因是另一个应用程序已经在使用蓝牙设备。我试图让我的连接失败,至少抛出异常或让我知道该设备已被其他应用程序使用。

任何其他建议来解决这个问题?

谢谢。

+0

没有人有想法吗? – Jesse 2012-03-01 14:37:03

+0

你能解决它吗?我正面临类似的问题。 – 2014-11-21 08:01:54

回答

0

你为什么叫Thread.Sleep? BluetoothSocket.connect是一个阻塞呼叫。这意味着你的Thread.Sleep不会被调用,直到连接返回成功连接或抛出异常。

你是在打个招呼吗?因为这会影响你的活动。你应该有3个线程来处理蓝牙,接受线程,连接线程和连接的线程。就像在这里的BluetoothChat示例中一样:

http://developer.android.com/resources/samples/BluetoothChat/index.html