[英]How to use Inputstream with Handler
我不明白我应该如何使用Inputstream和Handler。
我希望有人能解释一下。 我阅读了一些教程,但我理解它们的作用,但不了解它们的作用。
这是我不明白的例子:
public void run() {
int ret = 0;
byte[] buffer = new byte[16384];
int i;
while (true) { // read data
try {
ret = mInputStream.read(buffer);
} catch (IOException e) {
break;
}
i = 0;
while (i < ret) {
int len = ret - i;
if (len >= 1) {
Message m = Message.obtain(mHandler);
int value = (int)buffer[i];
// &squot;f&squot; is the flag, use for your own logic
// value is the value from the arduino
m.obj = new ValueMsg(&squot;f&squot;, value);
mHandler.sendMessage(m);
}
i += 1; // number of bytes sent from arduino
}
}
}
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
ValueMsg t = (ValueMsg) msg.obj;
// this is where you handle the data you sent. You get it by calling the getReading() function
mResponseField.setText("Flag: "+t.getFlag()+"; Reading: "+t.getReading()+"; Date: "+(new Date().toString()));
}
};
对不起我的英语不好
好的,我将尝试在问题和评论中回答您的问题。
首先:使用byte[]
在InputStream
上调用read()
会将字节读入缓冲区。
byte[] myBuffer = new byte[16384];
myInputStream.read(myBuffer);
此代码将从读取的字节inputstream
和将其存储在byte[]
称为myBuffer
。 它不是从缓冲区读取。
在此处查看InputStream
的文档,或者:
从输入流中读取一定数量的字节,并将其存储到缓冲区数组b中。
其次:
该代码的作用(没有看到其余的代码)是,它开始在后台线程上读取输入inputstream
。 每次将在此处读取一个字节:
ret = mInputStream.read(buffer);
为了能够从后台线程更改视图,我们将需要某种机制在后台线程和UI线程之间建立桥梁,因为只有UI线程才能更改视图。
进来的处理程序 :-)
引用从Handler
文档:
[...]使要在与您自己的线程不同的线程上执行的操作排队。
因此,在您的代码中,您将“获取”与您的UI线程关联的当前Handler
:
Message m = Message.obtain(mHandler); // Obtain the UI thread handler.
int value = (int)buffer[i]; // Read data.
m.obj = new ValueMsg(&squot;f&squot;, value); // Create a message to send to the UI thread handler.
mHandler.sendMessage(m); // Send the message to the UI thread handler.
之后,UI线程Handler
在handleMessage
方法内接收到消息:
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
ValueMsg t = (ValueMsg) msg.obj;
// this is where you handle the data you sent. You get it by calling the getReading() function
mResponseField.setText("Flag: "+t.getFlag()+"; Reading: "+t.getReading()+"; Date: "+(new Date().toString()));
}
并根据收到的消息采取行动,并在您选择的TextView
中显示该消息。
Handlers
在某种程度上是一个复杂的主题,但是在许多地方都需要Handlers
,当您开始使用多个线程并且大多数应用程序有时会开始使用多个线程时:-)
在旁注
可以使用其他东西,但可以使用处理程序。
在while循环内,它将message
到UI Handler
您可以使用名为runOnUiThread(runnable)
的便捷方法替换Handler
程序代码,以便您的代码如下所示:
while (i < ret) {
int len = ret - i;
if (len >= 1) {
runOnUiThread(new Runnable() {
int value = (int)buffer[i];
mResponseField.setText(String.valueOf(value));
});
}
i += 1; // number of bytes sent from arduino
}
请记住,上面的代码可能无法编译(我自己还没有尝试过...)。 您将必须位于Activity
或Fragment
,因为runOnUiThread
方法绑定到Activity
类。 另外,某些字段可能必须是final
字段才能从runOnUiThread
方法读取它们,但我希望您明白这一点:-)
希望这会有所帮助-否则让我知道,我将尽力阐述:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.