2012-06-24 34 views
0

我目前正在研究一个需要从蓝牙套接字读取数据的android应用程序。我使用的代码如下:从套接字读取数据问题,在Android应用程序中冻结UI

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上的数据,而不是在完成循环后显示数据。

感谢您的任何帮助提前。

问候,

查尔斯

回答

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. Butfrom 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 wascreated. 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 doeswork in a separate thread and post it on UI.

+0

你能不能给我如何使用单独的非UI线程的例子,并把数据回到UI线程? –

+0

亲爱的我现在在工作......我会在这里编辑我的文章,并给我希望的例子,只要我回家 –

+0

Ok.Thanks。我期待你的榜样。 –

1

InputStream.read()的Java says

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

你的UI被阻塞,因为你是从读在UI线程上的套接字。你应该明确地拥有另一个从套接字读取数据的线程,并将结果传递给用户界面进行动态更新。

0

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