Android BluetoothSocket-超时

Android BluetoothSocket-超时,第1张

Android BluetoothSocket-超时

为什么不尝试类似的东西

public class ReadTask extends Thread {  private byte[] mResultBuffer;  private Exception mCaught;  private Thread mWatcher;  public ReadTask(Thread watcher) {    mWatcher = watcher;  }  public void run() {    try {      mResultBuffer = sendAndReceive();    } catch (Exception e) {      mCaught = e;    }    mWatcher.interrupt();  }  public Exception getCaughtException() {    return mCaught;  }  public byte[] getResults() {    return mResultBuffer;  }}public byte[] wrappedSendAndReceive() {  byte[] data = new byte[1024];  ReadTask worker = new ReadTask(data, Thread.currentThread());  try {    worker.start();    Thread.sleep(6000);  } catch (InterruptedException e) {    // either the read completed, or we were interrupted for another reason    if (worker.getCaughtException() != null) {      throw worker.getCaughtException();    }  }  // try to interrupt the reader  worker.interrupt();  return worker.getResults;}

这里有一个

wrappedSendAndReceive()
极端的情况,即线程调用可能由于某种原因而不是ReadTask的中断而被中断。我想可以在ReadTask中添加完成的位,以允许另一个线程测试读取是否完成或中断是由其他原因引起的,但是我不确定这样做的必要性。

还要注意的是,此代码确实包含数据丢失的可能性。如果6秒钟到期并且已读取了一些数据,则最终将被丢弃。如果要解决此问题,则需要一次在ReadTask.run()中读取一个字节,然后适当地捕获InterruptedException。显然,这需要对现有代码进行一些重做以保持计数器并在接收到中断时适当调整读取缓冲区的大小。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5501283.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存