正如标题所解释的,我很难通过蓝牙将一些数据发送到我的电脑。我正试图将我的android手机作为客户端,将我的电脑作为服务器建立连接。当我试图通过BluetoothSocket.connect()建立连接时,我的手机会提示输入一个引脚。输入后,我的电脑也会提示输入相同的pin,但在我输入之前,connect()-方法会抛出IOException。我假设connect()-方法在我可以在电脑上输入正确的pin之前超时,但我如何让它等待足够长的时间来输入pin?
编辑:将电脑与手机重新配对后,它工作了,因为配对对话框不再出现在我的应用程序中。如果我打开电脑并启动我的应用程序,配对对话框会弹出,但几秒钟后就会消失,插座会抛出异常("对等重置连接")。显然,在配对完成之前,连接会被重置,但为什么呢?
这是我的代码:
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.");
}
如果有人能就这个问题给我一些好的建议,我会很高兴。
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);
}
}
试试这个。。。