我在使用BluetoothChat(我相信它在bot Java 和MonoForAndroid 上的代码相同)示例应用程序时遇到了一些问题。我已使用蓝牙模块将 Android 连接到微 Controller 。在发送消息(仅向微 Controller 发送原始字节)的情况下,它工作得很好!
微 Controller 传输恒定的串行消息,我想读取该数据。 BluetoothChat.cs 中有一个名为 MyHandler
的类具有如下代码块的应用程序:
case MESSAGE_READ:
byte[] readBuf = (byte[])msg.Obj;
// construct a string from the valid bytes in the buffer
var readMessage = new Java.Lang.String (readBuf, 0, msg.Arg1);
bluetoothChat.conversationArrayAdapter.Add(
bluetoothChat.connectedDeviceName + ": " + readMessage);
break;
所以我需要做的是处理传入的原始数据,然后更改一些按钮的颜色,因此我对上面的代码进行了以下更改:
case MESSAGE_READ:
byte[] readBuf = (byte[])msg.Obj;
//I have just added this code and it blocks the UI
bluetoothChat.ProcessIncomingData(readBuff);
break;
在 BluetootChat
Activity 中我有这个方法:
public void ProcessIncomingData(byte[] readBuf)
{
if (_logBox != null)
{
_logBox.Text += "\r\n"; //TextView
foreach (var b in readBuf)
{
_logBox.Text += (uint)b + " "; //Show the bytes as int value
}
}
}
`
但不幸的是,我所做的更改停止了 UI,并且应用程序在不久后崩溃了。
有什么想法可以在不卡住用户界面的情况下巧妙地做到这一点吗?
最佳答案
您需要将工作交给后台线程,以便让 UI 线程能够自由地响应输入。我不久前写了一篇文章,概述了一些可用于执行后台线程的不同方法:Using Background Threads in Mono For Android Applications
处理后台线程时要小心的一件事是,如果要对 UI 进行任何更改,则必须切换回 UI 线程。您可以使用 RunOnUiThread()
方法来执行此操作。
关于c# - 防止 UI 在处理数据时卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14148699/