我正在编写一个连接到蓝牙设备的 Android 应用程序,读取从设备发送的数据,将其添加到AChartEngine图表,并在 TextView 中显示数据。
我的蓝牙代码与 BluetoothChat 示例代码中的线程实现非常相似(它与 SDK 一起提供)。我可以在 LogCat 中看到ConnectedThread
循环正在执行并因此获取新数据,但是我的 TextView 在 7 行后停止更新,并且图形间歇性地暂停(更不用说它只是间歇性地响应交互)。LogCat 中没有显示任何错误。此外,如果我删除图表,TextView 的问题仍然存在。
为什么从我的其他线程更新时我的 UI 线程不工作?
以下是我的代码的相关部分。通过蓝牙发送的每个字符串都被接收ConnectedThread
并发送到BluetoothController.addToGraph()
,然后NewPoints
AsyncTask
从viewer
类中运行。
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;
}
}
}
是什么赋予了?如果需要更多代码,请告诉我。