正如标题所解释的那样,我很难通过蓝牙将一些数据发送到我的电脑上。我正在尝试建立与我的Android手机连接作为客户端和我的PC作为服务器。当我尝试通过BluetoothSocket.connect()实际建立连接时,我的手机会提示输入引脚。输入后我的PC也会提示相同的引脚,但在我输入之前,connect() - 方法会抛出IOException。我假设在我可以在我的电脑上输入正确的引脚之前,connect() - Method超时,但我怎么能让它等待足够长的时间让我输入PIN?
编辑:将PC与我的手机重新配对后,它工作正常,因为配对对话框不再出现在我的应用程序中。如果我取消配对PC并启动我的应用程序,配对对话框会弹出但几秒钟后会消失,并且套接字会抛出异常(“通过对等方重置连接”)。显然在配对完成之前重置了连接,但为什么呢?
这是我的代码:
private void connectToDevice(BluetoothDevice device)
{
mBluetoothAdapter.cancelDiscovery();
BluetoothSocket socket = null;
try
{
socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101- 0000- 1000-8000-00805F9B34FB"));
}
catch (IOException e)
{
Log.e("HeliRemote", "Couldn't get socket.");
return;
}
try
{
socket.connect();
}
catch (IOException e)
{
try
{
socket.close();
}
catch (IOException e1)
{
Log.e("HeliRemote", "Couldn't close connection");
}
// That's the message I get in LogCat
Log.e("HeliRemote", "Couldn't connect to Socket.");
return;
}
Log.i("HeliRemote", "connected.");
}
如果有人能就这个问题给我任何好的建议,我会很高兴。
答案 0 :(得分:1)
Method m = mBluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
mBluetoothSocket = (BluetoothSocket) m.invoke(mBluetoothDevice, 1);
// mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
}
catch (IOException eConnectException)
{
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
} catch (SecurityException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
} catch (NoSuchMethodException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
} catch (IllegalArgumentException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
} catch (IllegalAccessException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
} catch (InvocationTargetException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
}
}
尝试这个...