gpt4 book ai didi

java - Android无法通过蓝牙接收所有字符

转载 作者:太空宇宙 更新时间:2023-11-04 13:00:44 25 4
gpt4 key购买 nike

我正在创建一个应用程序,通过蓝牙使用 arduino 发送和接收数据。发送工作正常,但是当接收数据时,我没有收到发送的字符串的前几个字符。我总是得不到第一个字符,第二个我有时得到它,第三个我几乎总是得到它,等等。

例如,如果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/cdjW4Y1VXML 布局文件 http://pastebin.com/Ruf5euPP

单击第一个按钮连接到 arduino,然后单击第二个按钮发送字符串并开始接收数据。

所以是的,我完全不知道为什么它不起作用。它与 TerminalBT 配合得很好,所以这不是 arduino 的问题,而是我的应用程序的问题,但为什么我会随机收到字符?

最佳答案

我注意到的一件事是你不应该使用 10 作为分隔符。

我以前遇到过这个错误,如果你使用 10,有时它无法被正确识别。

您应该使用标准 Java 函数来解析分隔符。

System.getProperty("line.separator");

//OR

System.lineSeparator();

关于java - Android无法通过蓝牙接收所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34970603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com