android - 仅等待输入 X 时间

标签 android io wait

我正在尝试从输入流中读取数据,但如果程序在 X 时间内没有接收到数据,我想终止尝试并返回 -1。我之前使用的是 Thread.sleep( X ) 但后来意识到这是一种完全不正确的方法。如果有人有任何想法,请告诉我。这是我从输入流中读取的代码...

            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer, 0, length);

                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(MainMenu.MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                // Start the service over to restart listening mode
                BluetoothService.this.start();
                //break;
            }

最佳答案

您可以使用 Future做这个。

首先,您需要一个将作为“ future ”值返回的类:

public class ReadResult {
    public final int size;
    public final byte[] buffer;

    public ReadResult(int size, byte[] buffer) {
         this.size = size;
         this.buffer = buffer;
    }
}

然后需要使用executor服务,使用get(long timeout, TimeUnit unit)像这样:

        ExecutorService service = Executors.newSingleThreadExecutor();
        Future<ReadResult> future = service.submit(new Callable<ReadResult>() {

            @Override
            public ReadResult call() throws Exception {
                bytes = mInStream.read(buffer, 0, length);
                return new ReadResult(bytes, buffer);
            }
        });

        ReadResult result = null;
        try {
            result = future.get(10, TimeUnit.SECONDS);
        } catch (InterruptedException e1) {
            // Thread was interrupted
            e1.printStackTrace();
        } catch (ExecutionException e1) {
            // Something bad happened during reading
            e1.printStackTrace();
        } catch (TimeoutException e1) {
            // read timeout
            e1.printStackTrace();
        }

        if (result != null) {
            // here you can use it
        }

这样你就可以实现你的目标。请注意,最好将 Callable 类子类化,该类将接受输入流作为构造函数参数,然后使用类变量。

关于android - 仅等待输入 X 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11887950/

相关文章:

java - 在 libgdx 中处理多点触控

Haskell:使用 Parsec 和 IO 解析文件

jQuery - 等待函数返回值

java - 创建一个类以从 Java 中的另一个类调用其 notify()

java - 如何使用 Java 和 Spring 在 REST Web 服务中 wait()?

android - ARCore 不显示对象的真实尺寸

java - LaunchMap 无法解析或不是字段

android - 在 android google play 中测试

javaCC 解析器生成器无法处理 EOF

java - 在检索图像时已为此响应调用 getOutputStream()