I have an application that uses the bluetooth to receive some data (bytes) from other device. everything is going well, but I have a small issue on receiving the bytes all together. After receiving the bytes I show them on a Toast just to test them. When the other device sends 10 bytes together (for example: "ABCDEFGHIJ"), the program will take the first byte "A" only and show it on a Toast, then go to the second iteration and read the other 9 bytes and show "BCDEFGHIJ" on the Toast. Here is my code:
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;
}
}
In the MainActivity, I have:
// 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;
// ...
}
}
};
How can I receive all the bytes together?!