从在处理数据冻结preventing UI [英] Preventing UI from freezing while processing data

查看:152
本文介绍了从在处理数据冻结preventing UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些问题,BluetoothChat(即我beleive它同样code对BOT Java和MonoForAndroid)示例应用程序。我已经连我的Andr​​oid使用蓝牙模块的微控制器。在发送消息(以微控制器只是原始字节)的情况下,它的工作原理就好了!

I am having some problems with BluetoothChat (that I beleive its the same code on bot Java and MonoForAndroid) example app. I have connected my Android to an microcontroller using a Bluetooth module. In case of sending messages (just raw bytes to microcontroller) it works just fine!

微控制器流恒定的串行消息,我想读这些数据。有 MyHandler的 BluetoothChat.cs 应用程序,有一个code座是这样的:

The microcontroller streams a constant serial message and I want to read that data. There is a class named MyHandler in BluetoothChat.cs app that has a code block like this:

    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;

所以我需要做的是处理传入的原始数据,然后改变一些按钮的颜色,所以我做的follwing更改code以上:

So what I need to do is to process the incoming raw data and then change color of some buttons, So I made the follwing changes to the code above:

case MESSAGE_READ:
    byte[] readBuf = (byte[])msg.Obj;

         //I have just added this code and it blocks the UI
         bluetoothChat.ProcessIncomingData(readBuff);

    break;

而在 BluetootChat 活动我有这样的方法:

    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和f片刻后应用程序崩溃。

But unfortunately the changes I made stops the UI and the app crashes after f short while.

任何想法我怎么能做到这一点,而不整齐冻结用户界面?

Any ideas how can I do this neatly without freezing the UI?

推荐答案

您会希望手头的工作开了一个后台线程,以保持UI线程可以自由输入响应。我写了一个帖子一段时间回来,概述了一些做后台线程提供给您不同的方法:<一href=\"http://www.gregshackles.com/2011/04/using-background-threads-in-mono-for-android-applications/\"相对=nofollow>在单声道使用后台线程Android应用程序

You'll want to hand the work off to a background thread in order to keep the UI thread free to respond to input. I wrote up a post awhile back outlining some of the different methods available to you for doing background threads: Using Background Threads in Mono For Android Applications

一件事要小心后台线程处理时是,如果你想对UI进行任何更改,必须切换到UI线程。您可以通过使用 RunOnUiThread()办法做到这一点。

One thing to be careful with when dealing with background threads is that if you want to make any changes to the UI, you must switch back to the UI thread. You can do this by using the RunOnUiThread() method.

这篇关于从在处理数据冻结preventing UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆