Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/229.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android studio处理程序未正确读取蓝牙消息_Android_Bluetooth_Arduino_Type Conversion_Android Handler - Fatal编程技术网

Android studio处理程序未正确读取蓝牙消息

Android studio处理程序未正确读取蓝牙消息,android,bluetooth,arduino,type-conversion,android-handler,Android,Bluetooth,Arduino,Type Conversion,Android Handler,我通过蓝牙模块从arduino发送数据。我只是将不同的整数进行流式处理 int bluetoothData; //give value to bluetoothData Serial1.println(bluetoothData); 在我的Android代码中,我有一个蓝牙插座,用于接收来自arduino的数据。数据由处理程序处理。问题就在这里,有时数据被误读了。例如,我发送的是“100”,但处理程序将保存在我的数据库“000”中,或者我发送的是“194”,读取的是“994”。有时,这种阅

我通过蓝牙模块从arduino发送数据。我只是将不同的整数进行流式处理

int bluetoothData;

//give value to bluetoothData

Serial1.println(bluetoothData);
在我的Android代码中,我有一个蓝牙插座,用于接收来自arduino的数据。数据由处理程序处理。问题就在这里,有时数据被误读了。例如,我发送的是“100”,但处理程序将保存在我的数据库“000”中,或者我发送的是“194”,读取的是“994”。有时,这种阅读错误每15次就会发生一次。有时根本不会有任何错误。有人知道原因是什么吗?是蓝牙模块的某些硬件故障,还是我读取数据的方式等。以下是接收数据线程的Android代码:

final int RECIEVE_MESSAGE = 1;
...
mmInStream = socket.getOutputStream();
byte[] buffer = new byte[256];  // buffer store for the stream
int bytes; // bytes returned from read()

// Keep listening to the InputStream until an exception occurs
 while (true) {
 bytes = mmInStream.read(buffer); 
 h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();
 }
以下是处理程序本身的代码:

public void handleMessage(android.os.Message msg) {
        switch (msg.what) {
            case RECIEVE_MESSAGE:                                                   
                byte[] readBuf = (byte[]) msg.obj;
                String strIncom = new String(readBuf, 0, msg.arg1);                 
                sb.append(strIncom);                                                
                int endOfLineIndex = sb.indexOf("\r\n");                            
                if (endOfLineIndex > 0) {                                            
                    String sbprint = sb.substring(0, endOfLineIndex);               
                    sb.delete(0, sb.length());
                    btData = Integer.parseInt(sbprint);
                    M = btData;
                    insert = mDataBaseHelper.insert(M,DataBaseHelper.TABLE_Temp);
                }

您在每条消息中使用相同的缓冲区:
h.obtainMessage(receive_message,bytes,-1,buffer)
非常感谢您,从未考虑过这一点,它是有效的。为了避免创建1000s缓冲区,您可以使用
android.support.v4.util.poolls.SynchronizedPool
例如