我有一个应用程序使用蓝牙从其他设备接收一些数据(字节)。一切进展顺利,但我在接收所有字节时遇到了一个小问题。收到字节后,我将它们显示在 Toast 上只是为了测试它们。当另一个设备一起发送 10 个字节时(例如:“ABCDEFGHIJ”),程序将只取第一个字节“A”并将其显示在 Toast 上,然后转到第二次迭代并读取其他 9 个字节并显示“BCDEFGHIJ”在 toast 上。这是我的代码:
byte[] buffer = new byte[1024]; // Read 1K character at a time.
int bytes = 0; // Number of bytes.
while(true)
{
try
{
// Read from the InputStream.
bytes = bInStream.read(buffer);
// Send the obtained bytes to the MainActivity.
mainActivityHandler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
}
catch(IOException e)
{
connectionLost();
break;
}
}
在 MainActivity 中,我有:
// The Handler that gets information back from the BluetoothManager.
private final Handler handler = 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);
Toast.makeText(MainActivity.this, readMessage, Toast.LENGTH_SHORT).show();
break;
// ...
}
}
};
我怎样才能一起接收所有字节?!
最佳答案
嗯,罪魁祸首很可能是您发送消息的方式。您的接收没有问题,它将接收到写入的字节数(最多 1024 个)。
如果您无法控制消息的发送方式,您可能一次读取一个字节,然后在您点击预定义的终止符时向您发送一条处理程序消息。例如:“ABCDEFGHIJ#”,其中 # 是终止符。
String msg = "";
byte ch;
while((ch=mInStream.read())!='#') {
bytes++;
msg+=ch;
}
关于java - 如何通过蓝牙一起读取所有字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9231598/