栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Android BluetoothSocket-超时

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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。显然,这需要对现有代码进行一些重做以保持计数器并在接收到中断时适当调整读取缓冲区的大小。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/508892.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号