Android在蓝牙套接字上设置超时

时间:2016-08-13 20:39:31

标签: android multithreading sockets bluetooth socket-timeout-exception

在使用device.createRfcommSocketToServiceRecord(MY_UUID)创建的蓝牙套接字上,我希望在一定时间内没有任何内容到达时,运行一些代码,但仍然能够在它们到达时立即处理这些字节。

.setSoTimeout的{​​{3}}完全解释了我愿意做的事情:

  

如果将此选项设置为非零超时,则与此Socket关联的InputStream上的read()调用将仅阻止这段时间。如果超时到期,则引发java.net.SocketTimeoutException,尽管Socket仍然有效。

所以看起来这是将我的代码放在catch声明中的绝佳机会。

但遗憾的是.setSoTimeout根据我的Android Studio无法使用蓝牙套接字。如果没有这种方法,我该如何实现这样的功能呢?

Thread.sleep显然也不是一个选项,因为我无法锁定该帖子。

1 个答案:

答案 0 :(得分:2)

无论如何,我使用Thread.sleep解决了它,通过使用小间隔进行睡眠,因此试图模仿.setSoTimeout操作:

  • 短暂睡眠,检查传入数据,循环直到达到超时,然后执行超时代码。

我想有更好的解决方案,但现在可行。

当输入流上没有字节到达时,给定的代码将每秒执行“超时代码”(由int timeOut设置)。如果一个字节到达,则它会重置计时器。

// this belongs to my "ConnectedThread" as in the Android Bluetooth-Chat example
public void run() {
    byte[] buffer = new byte[1024];
    int bytes = 0;
    int timeOut = 1000;
    int currTime = 0;
    int interval = 50;
    boolean letsSleep = false;
    // Keep listening to the InputStream
    while (true) {
        try {
            if (mmInStream.available() > 0) {               // something just arrived?
                buffer[bytes] = (byte) mmInStream.read();
                currTime = 0;                               // resets the timeout

                // .....
                // do something with the data
                // ...

            } else if (currTime < timeOut) {               // do we have to wait some more?
                try {
                    Thread.sleep(interval);
                    } catch (InterruptedException e) {
                        // ...
                        // exception handling code
                    }
                currTime += interval;
                } else {                                   // timeout detected
                // ....
                // timeout code
                // ...
                currTime = 0;                              // resets the timeout
            }
        } catch (IOException e) {
            // ...
            // exception handling code
        }
    }
}