Android在蓝牙socket上设置超时时间

4
在使用device.createRfcommSocketToServiceRecord(MY_UUID)创建的蓝牙套接字上,当一段时间内没有数据到达时,我希望能运行一些代码,但仍然能够在数据到达时立即处理字节。 .setSoTimeout的说明正好解释了我想要做的事情:

将此选项设置为非零超时后,与此套接字关联的InputStream上的read()调用仅会阻塞此时间量。如果超时,将引发java.net.SocketTimeoutException,但Socket仍然有效。

因此,看起来这是在catch语句中放置我的代码的完美机会。
但不幸的是,根据我的Android Studio,.setSoTimeout无法在蓝牙套接字上工作。如何在没有这种方法的情况下实现这种功能?
显然,Thread.sleep也不是一个选项,因为我不能锁定线程。

你会使用一个处理器来做这个吗?我的意思是替换掉thread.sleep。 - Guo Xingmin
1个回答

3
我用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
        }
    }
}

也许有些人会说计时器更好,但这个也能用 :) - Peter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接