有谁知道如何在 API 级别 2.3.3 的 2 个 Android 设备之间创建不安全的 RFCOMM 连接,同时使用任意声明的服务名称?(不是随机的或更改的服务名称,只是我自己定义的服务名称)
细节
我正在尝试在 2 个 Android 设备之间创建不安全的 Rfcomm 连接:Droid X2 和 Asus Transformer。我假设这两种设备都具有 Android 2.3.3 级别的功能,以实际获得使用不安全 Rfcomm 的能力。
当我尝试按照此处所述创建蓝牙连接时,使用现在公共的 createInsecureRfcommSocketToServiceRecord() 和 listenUsingInsecureRfcommWithServiceRecord(SERVICE, UUID),我收到报告:
java.io.IOException: Service discovery failed
at android.bluetooth.BluetoothSocket$SdpHelper.doSdp(BluetoothSocket.java:377)
at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:201)
at com.s4d.bluenomad.DeviceConnections$ClientThread.run(DeviceConnections.java:406)
我发现了一个相关的问题,其中创建正常连接的人收到此错误并使用反射来调用私有方法。但是,我不知道现在哪种私有方法对应于启动“不安全”连接。我尝试使用该相关问题中提出的解决方案,但 Android 要求我配对设备,这正是我需要避免的。我真的需要不安全的方法。
我什至尝试了此处概述的官方解决方案和黑客解决方案的组合
相关代码片段
创建 ServerThread 来监听连接
Log.i(TAG, "Constructing a ServerThread");
// Use a temporary object that is later assigned to serverSocket,
// because serverSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = btAdapter.listenUsingInsecureRfcommWithServiceRecord(SERVICE_NAME, SERVICE_UUID);
Log.i(TAG,"Started listening on insecure RFCOMM channel for service requests for: " + SERVICE_NAME);
} catch (IOException e) { }
serverSocket = tmp;
ServerThread 监听连接
BluetoothSocket socket;
while(true)
{
try
{
socket = serverSocket.accept();
}
catch( IOException e)
{
break;
}
if( socket != null )
{
Log.i(TAG, "Received new socket connection requesting service: " + SERVICE_NAME);
}
else
{
Log.i(TAG, "Socket connection attempted, but socket received is NULL.");
}
}
创建 ClientThread 以启动连接
Log.i(TAG, "Constructing a ClientThread");
BluetoothSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createInsecureRfcommSocketToServiceRecord(SERVICE_UUID);
Log.i(TAG,"Created client socket on insecure RFCOMM channel for service requests for: " + SERVICE_NAME);
}
catch (IOException e)
{
Log.i(TAG, "Failed to createInsecureRfcommSocket() against MAC: " + device.getAddress());
}
clientSocket = tmp;
ClientThread 连接服务器
try
{
clientSocket.connect();
}
catch( final IOException e)
{
DeviceConnections.this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
console.append("Client unable to connect to service.");
Log.i(TAG, "Client socket unable to connect() to: " + clientSocket.getRemoteDevice().getAddress());
e.printStackTrace();
}
});
}
我确实得到了日志输出“客户端套接字无法连接()到:[MY_MAC_ADDRESS]”,然后我得到了“服务发现失败”异常的堆栈跟踪。