【问题标题】:Android set timeout on a bluetooth socketAndroid 在蓝牙套接字上设置超时
【发布时间】:2016-12-20 13:55:08
【问题描述】:

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

.setSoTimeoutdescription 准确地解释了我愿意做什么:

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

因此,将我的代码放入 catch 语句中似乎是绝佳机会。

但不幸的是,根据我的 Android Studio,.setSoTimeout 不适用于蓝牙套接字。如果没有这种方法,我如何实现这样的功能?

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

【问题讨论】:

  • 你会使用处理程序来做到这一点,我的意思是替换 thread.sleep。

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


【解决方案1】:

无论如何,我还是用 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
        }
    }
}

【讨论】:

  • 也许有些人会说 Timer 会更好,但这个工作:)
猜你喜欢
  • 1970-01-01
  • 2014-03-27
  • 1970-01-01
  • 2017-05-25
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-18
相关资源
最近更新 更多