我写Android应用连接到蓝牙设备更新,读取从设备发送的数据,把它添加到一个AChartEngine曲线图,在一个TextView显示数据。的Android UI线程停止从其他线程
我的蓝牙代码非常类似于BluetoothChat示例代码(它配备了SDK)的线程实现。我可以看到在LogCat中,ConnectedThread
循环正在执行并因此获取新数据,但我的TextView在7行和之后停止更新,图表间歇性地暂停(更不用说它只是间歇性地响应交互)。 LogCat中没有显示任何错误。另外,如果我删除图形,TextView的问题仍然存在。
从我的其他线程更新的时候为什么不工作我的UI线程?
以下是我的代码的相关部分。送过来蓝牙每个串在ConnectedThread
被接收并被发送到BluetoothController.addToGraph()
,然后运行从viewer
类NewPoints
AsyncTask
。
private class ConnectedThread extends Thread {
public ConnectedThread(BluetoothSocket socket, String socketType) { ... } // Initialize input and output streams here
public void run() {
while (true) {
Log.i(TAG, "READ mConnectedThread");
// Read from the InputStream
byte[] buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothController.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
Log.i(TAG, "LOOPEND mConnectedThread");
}
}
}
public class BluetoothController extends Activity {
private viewer plotter;
public static final int MESSAGE_READ = 2;
// The Handler that gets information back from the BluetoothClass
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
addToGraph(readMessage);
break;
}
}
};
protected void addToGraph(String result) {
// process the string, create doubles x and y that correspond to a point (x,y)
plotter.new NewPoints().execute(x, y);
}
}
public class viewer extends Activity {
// initialize graph, etc.
@Override
protected void onResume() {
// Create handlers for textview
textHandler = new Handler();
// Set scrolling for textview
myTextView.setMovementMethod(new ScrollingMovementMethod());
protected class NewPoints extends AsyncTask<Double, Void, Void> {
@Override
protected Void doInBackground(Double... values) {
mCurrentSeries.add(values[0], values[1]); // x, y
if (mChartView != null) {
mChartView.repaint();
}
final Double[] messages = values;
textHandler.post(new Runnable() {
@Override
public void run() {
myTextView.append("(" + messages[0].toString() + ", " + messages[1].toString() + ") \n");
}
});
return null;
}
}
}
什么给?如果需要更多代码,请告诉我。
我还没有看到完整的源代码。只是一个想法。可能是错的。你不应该在你的连接线程中使用睡眠? – san 2012-08-01 03:47:22