重新分配输入/输出流?

时间:2012-12-14 12:32:19

标签: java android stream inputstream outputstream

我正在尝试使用android中的库连接到终端模拟器,这将连接到串行设备,并应显示发送/接收的数据。要附加到终端会话,我需要提供inputstreamsetTermIn(InputStream)outputstreamsetTermOut(OutputStream)

我在onCreate()初始化并附加了一些像这样的流,这些只是初始流,并没有附加到我想要发送/接收的数据上。

private OutputStream bos;
private InputStream bis;

...

byte[] a = new byte[4096];
bis = new ByteArrayInputStream(a);
bos = new ByteArrayOutputStream();
session.setTermIn(bis);
session.setTermOut(bos);
/* Attach the TermSession to the EmulatorView. */
mEmulatorView.attachSession(session);

我现在想在发送和接收数据时将数据流分配给数据,但我认为我做错了。在sendData()方法中,每次按Enter键时都会调用,我有:

public void sendData(byte[] data)
{
        bos = new ByteArrayOutputStream(data.length);         
}

并在onReceiveData()方法中,每次通过串行接收数据时调用:

public void onDataReceived(int id, byte[] data)
{
        bis = new ByteArrayInputStream(data);           
}

我的终端屏幕上没有看到任何数据,但我正在通过串口成功发送和接收数据。所以我的问题是,我应该每次发送和接收数据时设置流,还是只设置一次。我还需要在某个地方再次将它们附加到终端会话mEmulatorView.attachSession(session),还是应该将新流自动发送到屏幕?

我的理论是我的终端连接到旧流,这就是我无法在终端屏幕上看到数据的原因。这是正确的吗?

我尝试使用boolean和if语句在每个方法中设置新的输入/输出流一次,但后来我在logcat中收到警告消息

RuntimeException 'sending message to a Handler on a dead thread'

我已经根据回答编辑了它来写和rad,但是我注意到库有它自己的写入方法来向终端提供数据,所以我甚至不知道这些流是什么,如果那是case,我需要写这个写入模拟器吗?

public void write(byte[] data,
              int offset,
              int count)
Write data to the terminal output. The written data will be consumed by the emulation     client as input.
write itself runs on the main thread. The default implementation writes the data into a     circular buffer and signals the writer thread to copy it from there to the OutputStream.

Subclasses may override this method to modify the output before writing it to the  stream, but implementations in derived classes should call through to this method to do the  actual writing.

Parameters:
data - An array of bytes to write to the terminal.
offset - The offset into the array at which the data starts.
count - The number of bytes to be written.

1 个答案:

答案 0 :(得分:1)

java中的对象通过引用传递,因此如果你这样做

bos = new ByteArrayOutputStream(data.length)

你实际上是丢弃了之前的输出流并创建了一个新的输出流。

尝试保持对输入和输出流的引用并将数据写入其中,例如:

bos.write(data);
相关问题