1

我正在尝试从输入流中读取数据,但如果程序在 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;
            }
4

2 回答 2

1

您可以使用Future来执行此操作。

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

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

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

然后你需要使用执行器服务并使用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
        }

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

于 2012-08-10T09:16:14.377 回答
0

您可以启动一个新线程并在那里等待 x 时间。传递对您的活动的引用,一旦时间结束,您可以从时间线程调用活动中的方法。

例如。

Thread time = new Thread() {

Activity foo;

public addActivity(Activity foo) {
this.foo = foo;
}

public void run() {
Thread.sleep(x);
// Once done call method in activity
foo.theTimeHasCome();
}

}.start();

我希望这有帮助!

于 2012-08-09T16:41:23.563 回答