我正在为英飞凌XMC4500微处理器编写嵌入式应用程序。 我从不同的传感器读取数据,我通过蓝牙模块发送这些数据,以便在Android smarphone的屏幕上显示它们。我使用GraphView库。
我根据Android教程实现了BluetoothClass。如果我从单个传感器获取数据,那么一切都很好。但是当我从多个传感器获取数据时,我的应用程序无法顺利运行。
当然我在单独的线程中进行蓝牙连接,我尝试在Handler中更新UI。 请告诉我,我做错了什么。当然,我通过JSON交换格式发送数据:
我从微控制器方面发送了类似的东西:
sprintf(json_data, "{"
"\"m\":"
"["
"{"
"\"id\":a,"
"\"x\":%.2f,"
"\"y\":%.2f,"
"\"z\":%.2f"
"},"
"{"
"\"id\":g,"
"\"x\":%.2f,"
"\"y\":%.2f,"
"\"z\":%.2f"
"},"
"{"
"\"id\":m,"
"\"x\":%.2f,"
"\"y\":%.2f,"
"\"z\":%.2f"
"},"
"{"
"\"id\":t,"
"\"x\":%.2f"
"},"
"{"
"\"id\":h,"
"\"x\":%.2f"
"}"
"]"
"}", getAccelXf(), getAccelYf(), getAccelZf(), getGyroXf(), getGyroYf(), getGyroZf(), getMagnetXf(), getMagnetYf(), getMagnetZf(), readTemperature(), readHumidity());
作为我的请求的附件,我添加了一些源代码:
public class ConnectedThread extends Thread
{
BluetoothSocket connectedSocket;
InputStream inStream;
OutputStream outStream;
public ConnectedThread(BluetoothSocket socket)
{
connectedSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try
{
if (connectedSocket != null)
{
tmpIn = connectedSocket.getInputStream();
tmpOut = connectedSocket.getOutputStream();
mHandler.obtainMessage(Constants.MESSAGE_DEVICE_CONNECTED_SUCCESSFULLY).sendToTarget();
// Toast.makeText(activityContext, "connectedSocket != null", Toast.LENGTH_LONG);
}
}
catch (IOException e) {
mHandler.obtainMessage(Constants.MESSAGE_INPUT_OUTPUT_STREAM_UNAVAILABLE).sendToTarget();
e.printStackTrace();
}
inStream = tmpIn;
outStream = tmpOut;
}
public void run()
{
if(bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();
}
byte[] buffer = new byte[4096];
int bytes;
String dupa;
while (true)
{
try {
if (inStream != null)
{
bytes = inStream.available();
if(bytes > 0 && bytes <= 200)
{
byte[] pocketBytes = new byte[bytes];
inStream.read(pocketBytes);
//Log.d(TAG, "setState() " + mState + " -> " + state);
System.out.println(pocketBytes.toString());
dupa = pocketBytes.toString();
System.out.println(dupa);
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, pocketBytes).sendToTarget();
}
}
} catch (IOException e) {
mHandler.obtainMessage(Constants.MESSAGE_REMOTE_DEV_DISCONNECTED).sendToTarget();
break;
}
/*try
{
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
outStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
connectedSocket.close();
} catch (IOException e) { }
}
}
}
然后我尝试在Handler中更新UI。
这是我申请样本的链接:
https://www.youtube.com/watch?v=_Buv64vADNk&feature=youtu.be
它不能顺利运行,有时候它没有响应。
你可以告诉我我做错了什么吗? Thx提前。答案 0 :(得分:0)
Mateusz;查看操作块会强制您的代码进入后台,其优先级低于UI代码。您也可以尝试GCD。这是一个非常简单的代码块,作为一个单独的进程分离出来。
How to determine when all images have been downloaded from a set in Swift?
将UI代码置于最高优先级,将蓝牙置于最低优先级;确保您在UI更新中所做的唯一陈述是这样做的,不要在那里放置任何不更新UI的内容。