简体   繁体   中英

Bluetoothsocket timeout on read and write

I'm designin an application in Android that connects the mobile to a bluetooth device. I can do this, as I open a BluetoothSocket like this:

Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
socket = (BluetoothSocket) m.invoke(device, 1);
socket.connect();

Where device is the paired device with the mobile bluetooth desired. The thing is, this external device is a bit special, and it has different times for writing and answering to the mobile, so I need to put some timeouts on my socket for reading and writing, but I've searched a lot and it seems like BluetoothSocket doesn't support this.

Can anybody tell me a different way to admin timeouts on reading and writing to the port on the BluetoothSocket class for Android?

Thank you!

There are many Exceptions a socket or it's streams can throw. The socket.connect() for example can throw a ConnectTimeoutException . Every method in the BluetoothSocket context can through an IOException just take a look at the documentation and you will see which exception you have to catch in order to make your program work properly.

Here is the code for reading and writing code:

Writng code on port:

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);
}

Then, reading from port until response available:

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;
     }
}

The thing is that I think the writing works, as I convert the desired string into bytes, and it works. But then, when I'm waiting for response, it mixes further responses with the desired, and I think this is because timings.

There's no more code in the middle related with sockets. First, I create it. Then, I try to send a byte String. Then I wait until I receive the answer for the byte String that I just sent.

Thank you in advance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM