我正在通过蓝牙创建一个通过arduino发送和接收数据的应用程序。发送工作正常,但是当收到数据时,我没有收到发送字符串的前几个字符。我总是没有得到第一个字符,第二个我有时得到它,第三个我几乎总是得到它,等等。Android无法通过蓝牙接收所有字符
因此,例如,如果arduino发送“OK 1”,我收到“K 1”或“ 1“或”1“,但绝不是完整的字符串。一个简单的解决方法是添加几个虚拟角色,但这是一个蠢事。
这里的监听传入连接的处理方法,直接复制/ Android sample bluetooth code to send a simple string via bluetooth粘贴(尽管有一些修正):
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
final boolean stopWorker = false;
final int readBufferPosition = 0;
final byte[]readBuffer = new byte[1024];
Thread workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = inStream.available();
int readBufferPosition2 = readBufferPosition;
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
inStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition2];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes);
readBufferPosition2 = 0;
handler.post(new Runnable()
{
public void run()
{
result.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition2++] = b;
}
}
}
}
catch (IOException ex)
{
}
}
}
});
workerThread.start();
}
这里是我的情况下,所有的代码要测试它(警告:很多虚拟的和过时的代码):
MainActivity.java http://pastebin.com/cdjW4Y1V XML布局文件http://pastebin.com/Ruf5euPP
点击第一个按钮连接到Arduino并点击第二按钮发送一个字符串并开始接收数据。
所以,我完全不知道为什么它不起作用。它与TerminalBT工作正常,所以它不是与Arduino的问题,这是我的应用程序的问题,但为什么我随机接收字符?
我该如何使用此功能?我在哪里把它放在我的代码中? – Zezombye
你这样做.byte b = packetBytes [i] ;.只需比较一个.equals(System.lineSeparator())函数即可。如果您需要将字节转换为我无法检查自己的字符串 – Neo