![](/img/trans.png)
[英]Implement a timeout in BluetoothSocket inputstream.read() in Android
[英]Bluetoothsocket timeout on read and write
我正在设计一个Android中的应用程序,该应用程序将移动设备连接到蓝牙设备。 我可以这样做,就像我打开一个BluetoothSocket一样:
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
socket = (BluetoothSocket) m.invoke(device, 1);
socket.connect();
其中device是具有所需移动蓝牙的配对设备。 事实是,此外部设备有点特殊,它在移动设备上进行书写和应答的时间不同,因此我需要在套接字上放置一些超时时间以进行读写,但是我进行了很多搜索,而且看起来像BluetoothSocket不支持此功能。
有人可以告诉我用于Android的BluetoothSocket类的端口上读写超时的另一种管理方式吗?
谢谢!
套接字或其流可能抛出许多异常。 例如, socket.connect()
可以抛出ConnectTimeoutException 。 BluetoothSocket上下文中的每个方法都可以通过IOException
查看文档 ,您将看到必须捕获哪个异常才能使程序正常工作。
这是用于读取和编写代码的代码:
在端口上编写代码:
try
{
// Enviamos los bytes
DataOutputStream dOut = null;
dOut = new DataOutputStream(socket.getOutputStream());
// Send message
dOut.writeBytes(res);
dOut.flush();
}
catch (IOException e)
{
Dialogs.showErrorDialog("Error al recuperar la fecha y hora del dispositivo Nonin.", this);
}
然后,从端口读取直到响应可用:
DataInputStream dIn = null;
// We receive the answer
try
{
dIn = new DataInputStream(socket.getInputStream());
}
catch (IOException e)
{
Dialogs.showAlertDialog("An exception occured during bluetooth io stream creation", this);
}
while (true)
{
try
{
String data = dIn.readLine(); // readLine();
byte[] total = EncodingUtils.getBytes(data, "ASCII");
Dialogs.showInfoDialog("Mensaje ok: " + data.toString(), this);
}
catch (IOException e)
{
break;
}
}
事实是,我认为写作是有效的,因为我将所需的字符串转换为字节,并且可以正常工作。 但是,当我等待响应时,它将进一步的响应与所需的响应混合在一起,我认为这是因为时间安排。
中间没有更多与套接字相关的代码。 首先,我创建它。 然后,我尝试发送一个字节字符串。 然后,我等待直到收到刚发送的字节字符串的答案。
先感谢您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.