简体   繁体   中英

Bluetooth InputStream.read() doesn't return Data and Blocks forever

I've got some problems with Android Bluetooth stuff. When I call

bytes = mmInStream.read(buffer);

It usually works as it should. On the Cat B15 smartphone however, the read method sometimes blocks forever, even though the connection is still running and data should be arriving. I have temporarily solved the problem by this code:

while (true) {

    int available = 0;

    try {
        available = mInStream.available();
    } catch (IOException e) {}

    if (available > 0) {
        try {
            bytes = mInStream.read(buffer);
            ioExceptionsCounter = 0;
            // [send the obtained bytes to the UI activity]
            // ...............
        } catch (IOException e) {
            ++ioExceptionsCounter;
            if (ioExceptionsCounter >= 4) {
                break;
            }
        }
    }

    try {
        Thread.sleep(10);
    } catch (InterruptedException e) {}
}

I dont think that the ioExceptionsCounter is really necessary but there was some complaints that it sometimes disconnects without reason so I thought one IOException might not be enough to close the connection.

What I really don't like about this is that it uses polling. It does work now on the Cat phone but it doesn't make me happy that all the other devices now execute this ugly code.

Do you have any ideas why this could be? Is this just a bug of the phone? By the way it runs ICS but it is definitely device specific.

I'm inclined to think that you are encountering a hardware-specific bug.

The various InputStream.read() methods are documented to block until at least one byte is read, or the end of the stream is detected, or an error occurs. If the read() sometimes blocks forever for you in the event that no bytes are available when it is first invoked, then that's definitely a bug outside your own code.

Also, it's highly questionable to ignore any number of IOException s, either from available() or from read() . After the stream throws an exception you cannot be confident of the integrity of anything you afterward might manage to read from it. I would normally expect such attempts at further reading also to throw IOException s. If you are getting spurious IOException s on the Cat B15, such that simply retrying your read() successfully obtains the correct data, then that is also a bug (maybe another facet of the same one).

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