0

我目前正在开发一个需要从蓝牙套接字读取数据的 android 应用程序。我正在使用的代码如下:

runOnUiThread(new Runnable() {
    public void run()
    {
        try{
            ReadData();
    }catch(Exception ex){}
    }
});
public void ReadData() throws Exception{
    try {
        b1 = new StringBuilder();
        stream = socket.getInputStream();
        int intch;
        String output = null;
        String k2 = null;
        byte[] data = new byte[10];
        // read data from input stream if the end has not been reached
        while ((intch = stream.read()) != -1) {
            byte ch = (byte) intch;
            b1.append(ByteToHexString(ch) +"/");
            k++;
            if(k == 20) // break the loop and display the output
            {
                output = decoder.Decode(b1.toString());
                textView.setText(output);
                k=0;
                break;
            }
        }
        // close the input stream, reader and socket
        if (stream != null) {
            try {stream.close();} catch (Exception e) {}
            stream = null;
        }
        if (socket != null) {
            try {socket.close();} catch (Exception e) {}
            socket = null;
        }
    } catch (Exception e) {
    }
}

但是,当我在 android 设备上运行应用程序时,UI 不会自动更新并且一直冻结。有谁知道如何解决 UI 冻结问题?我想在 UI 上动态显示数据,而不是在完成循环后显示数据。

感谢您提前提供任何帮助。

问候,

查尔斯

4

3 回答 3

1

InputStream.read()java上

此方法阻塞,直到输入数据可用

您的 UI 正在阻塞,因为您正在从 UI 线程上的套接字读取。您肯定应该有另一个线程从套接字读取数据并将结果传递给 UI 以进行动态更新。

于 2012-06-24T16:21:03.743 回答
0

您应该在非 UI 线程上运行 ReadData() 方法,然后一旦数据可用,就使用 runOnUIthread 机制在 UI 线程上运行 textView 的结果更新。

于 2012-06-24T16:36:24.440 回答
0

试试这个,

这个怎么运作。

1. When Android Application starts you are on the UI Thread. Doing any Process intensive work on this thread will make your UI unresponsive.

2. Its always advice to keep UI work on UI Thread and Non-UI work on Non-UI Thread. But from HoneyComb version in android it became a law.

你的代码有什么问题。

1. You are reading the data on the UI thread, making it wait to finish reading.. here in this line...而 ((intch = stream.read()) != -1))。

如何解决:

1. Use a separate Non-UI thread, and to put the value back to the UI thread use Handler.

2. Use the Handler class. Handler creates a reference to the thread on which it was created. This will help you put the work done on the Non-UI thread back on the UI thread.

3. Or use AsyncTask provided in android to Synchronize the UI and Non-UI work,which does work in a separate thread and post it on UI.

于 2012-06-24T16:39:53.393 回答