簡體   English   中英

重新分配輸入/輸出流?

[英]Reassign input/output stream?

我正在嘗試使用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)某個地方,還是應該將新流自動發送到屏幕?

我的理論是我的終端連接到舊的流,這就是為什么我無法在終端屏幕上看到數據的原因。 這是正確的嗎?

我嘗試使用布爾值和if語句在每種方法中僅設置一次新的輸入/輸出流,但是隨后我在logcat中收到警告消息

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

我已經根據答案將其編輯為write和rad,但是我注意到該庫具有將數據饋送到終端的自己的write方法,因此,即使是這種情況,我什至都不知道流是干什么的,並且我需要此寫操作才能寫入模擬器嗎?

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.

Java中的對象是通過引用傳遞的,因此如果您這樣做

bos = new ByteArrayOutputStream(data.length)

您實際上是在丟棄先前的輸出流並創建一個新的輸出流。

嘗試保持對輸入和輸出流的引用,並將數據寫入其中,例如:

bos.write(data);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM