2017-07-22 14 views
1

问题

如何可以暂时无法建立与远程Android装置因为蓝牙连接之间进行区分:区分“超出范围”或“范围内,但没有侦听服务器套接字”? (蓝牙)

  • 场景1:远程设备超出范围,或它的蓝牙已禁用。
  • 方案2:远程设备处于范围内,但远程设备上没有用于接受我的连接的服务器套接字。

我已经试过

  1. 我不能连接时抛出的异常区别,因为它在这两种情况下扔相同的例外:

    java.io.IOException: read failed, socket might closed or timeout, read ret -1 
    
  2. 我做不到使用fetchUuidsWithSdp()来检查我的UUID是否支持远程设备,因为它的行为VES以同样的方式在这两种情况下... according to the documentation

    这个API是异步的,并且{@link #ACTION_UUID}意图被发送,由远端支持的UUID。如果在获得SDP记录,或者如果这个过程需要很长的时间,{@link #ACTION_UUID}意图与当前存在于缓存中的UUID发送的错误...

    它的行为也根据this SO thread,似乎有点不可预测。

  3. 最后,我不想使用sdpSearch两个区分,因为这是在API 23中添加的,我希望能够向下支持API 19

回答

1

您可以通过尝试连接到Android设备上通常可用的标准UUID来确定设备是否在范围内。如果连接呼叫:

  • 失败,则远程设备超出范围或其蓝牙被禁用。
  • 成功,那么远程设备在范围内,你应该关闭连接,然后尝试连接到你的应用程序的UUID ...如果失败,那么没有侦听套接字...如果成功,那么所有好。

示例代码:

public BluetoothSocket connect(BluetoothDevice remoteDevice) throws IOException 
{ 
    OPP_UUID = UUID.fromString("00001105-0000-1000-8000-00805f9b34fb"); 

    // check if remote device is in range...throw exception if out of range 
    try 
    { 
     BluetoothSocket socket = remoteDevice 
      .createRfcommSocketToServiceRecord(OPP_UUID); 
     socket.connect(); 
     socket.close(); 
    } 
    catch(IOException ex) 
    { 
     throw new IOException("out of range",ex); 
    } 

    // try to connect to service on remote device...throw exception if UUID 
    // is not available 
    try 
    { 
     BluetoothSocket socket = remoteDevice 
      .createRfcommSocketToServiceRecord(MY_UUID); 
     socket.connect(); 
     return socket; 
    } 
    catch(IOException ex) 
    { 
     throw new IOException("no listening server socket",ex); 
    } 
} 

我以前BluetoothDevice.getUuids()让我的Android设备上的一个可用的UUID。它给了我这个名单:

0000110a-0000-1000-8000-00805f9b34fb - Advanced Audio Distribution Profile (0x110a) 
00001105-0000-1000-8000-00805f9b34fb - Object Push Profile (0x1105) // least invasive one...it seems 
00001115-0000-1000-8000-00805f9b34fb - Personal Area Networking Profile (0x1115) 
0000112f-0000-1000-8000-00805f9b34fb - Phonebook Access (0x112f) // this works! 
00001112-0000-1000-8000-00805f9b34fb - Headset - Audio Gateway (0x1112) 
0000111f-0000-1000-8000-00805f9b34fb - Handsfree Audio Gateway (0x111f) 
00001132-0000-1000-8000-00805f9b34fb - Message Access Profile (0x1132) // this works too! 
00000000-0000-1000-8000-00805f9b34fb - Base UUID (0x0000) // couldn't get this to work :(

Standard UUIDs from Bluetooth spec.