我有一个使用蓝牙接收来自其他设备的一些数据(字节)的应用程序。一切进展顺利,但我在收到所有字节时遇到了一个小问题。收到字节后,我会在Toast上显示它们,以便测试它们。当其它设备发送10个字节一起(例如:“ABCDEFGHIJ”),程序将采取的第一个字节的“A”仅,并显示在一个吐司,然后去第二次迭代和读出的其他9个字节,并显示“ BCDEFGHIJ“在吐司上。这里是我的代码:如何通过蓝牙一起读取所有字节?
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;
// ...
}
}
};
我怎样才能收到所有字节在一起?
我可以看到你是如何发送邮件?你在做类似bOutStream.write(“ABCDEFGHIJ” .getBytes()),或者是你写出来的人物之一,在一个时间? – broody 2012-02-10 17:03:11
蓝牙模块连接到arduino,所以我使用arduino软件的串行监视器发送消息。 – 2012-02-10 17:12:37