4

我编写了一个蓝牙 API 用于连接外部附件。API 的设计方式是有一堆阻塞调用,例如getTime, setTime, getVolume,setVolume等。这些工作的方式是它们创建一个有效负载来发送和调用一个被调用的方法,该方法sendAndReceive()会做一些准备工作并最终完成下列的:

byte[] retVal = null;
BluetoothSocket socket = getSocket();
// write
socket.getOutputStream().write(payload);
// read response
if(responseExpected){
    byte[] buffer = new byte[1024]; // buffer store for the stream
    int readbytes = socket.getInputStream().read(buffer);
    retVal = new byte[readbytes];
    System.arraycopy(buffer, 0, retVal, 0, readbytes);
}
return retVal;

问题是有时这个设备会变得很慢或没有响应,所以我想在这个调用上设置一个超时。我尝试了几种方法将此代码放入线程\未来任务并超时运行,例如:

FutureTask<byte[]> theTask = null;
// create new task
theTask = new FutureTask<byte[]>(
        new Callable<byte[]>() {

            @Override
            public byte[] call() {
                byte[] retVal = null;
                BluetoothSocket socket = getSocket();
                // write
                socket.getOutputStream().write(payload);
                // read response
                if(responseExpected){
                    byte[] buffer = new byte[1024]; // buffer store for the stream
                    int readbytes = socket.getInputStream().read(buffer);
                    retVal = new byte[readbytes];
                    System.arraycopy(buffer, 0, retVal, 0, readbytes);
                }
                return retVal;
            }
        });

// start task in a new thread
new Thread(theTask).start();

// wait for the execution to finish, timeout after 6 secs
byte[] response;
try {
    response = theTask.get(6L, TimeUnit.SECONDS);
} catch (InterruptedException e) {
    throw new CbtException(e);
} catch (ExecutionException e) {
    throw new CbtException(e);
} catch (TimeoutException e) {
    throw new CbtCallTimedOutException(e);
}
    return response;
}

这种方法的问题是我不能在调用方法中重新抛出异常,并且由于某些方法抛出异常我想转发回 API 的客户端,所以我不能使用这种方法。

你能推荐一些其他的选择吗?谢谢!

4

2 回答 2

2

您正在保存您不能使用 Future<> 方法,因为您想重新抛出异常,但实际上这是可能的。

大多数在线示例确实使用原型实现了 Callablepublic ? call()但只需将其更改为public ? call() throws Exception一切都会好的:您将在 theTask.get() 调用中获得异常,并且可以将其重新抛出给调用者。

我个人将 Executors 用于 android 上的蓝牙套接字超时处理:

protected static String readAnswer(...)
throws Exception {
    String timeoutMessage = "timeout";
    ExecutorService executor = Executors.newCachedThreadPool();
    Callable<String> task = new Callable<String>() {
       public String call() throws Exception {
          return readAnswerNoTimeout(...);
       }
    };
    Future<String> future = executor.submit(task);
    try {
       return future.get(SOCKET_TIMEOUT_MS, TimeUnit.MILLISECONDS); 
    } catch (TimeoutException ex) {
        future.cancel(true);
        throw new Exception(timeoutMessage);
    }
}
于 2012-09-21T09:09:03.200 回答
1

为什么不尝试类似的东西

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

于 2011-06-23T00:16:27.953 回答