Mattekr Mattekr - 5 months ago 84
Android Question

Xamarin Bluetooth InputStream not reading all the bytes (sometime)

I used this code to read the reply of a Bluetooth not LE device.

The solution is a Xamarin Forms project and the code is in the


using Android.Bluetooth;


public byte[] GetCommand()
byte[] rbuffer = new byte[200];

// Read data from the device
while (!_socket.InputStream.CanRead || !_socket.InputStream.IsDataAvailable())

int readByte = _socket.InputStream.Read(rbuffer, 0, rbuffer.Length);

catch (Java.IO.IOException e)

return rbuffer;

How is it possible to solve it?

Answer Source

I would use the following code instead:

//create new class for connect thread
  private class ConnectedThread extends Thread {
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

    //creation of the connect thread
    public ConnectedThread(BluetoothSocket socket) {
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        try {
            //Create I/O streams for connection
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;

    public void run() {
        byte[] buffer = new byte[256];
        int bytes; 

        // Keep looping to listen for received messages
        while (true) {
            try {
                bytes =;            //read bytes from input buffer
                String readMessage = new String(buffer, 0, bytes);
                // Send the obtained bytes to the UI Activity via handler
                bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
            } catch (IOException e) {
    //write method
    public void write(String input) {
        byte[] msgBuffer = input.getBytes();           //converts entered String into bytes
        try {
            mmOutStream.write(msgBuffer);                //write bytes over BT connection via outstream
        } catch (IOException e) {
            //if you cannot write, close the application
            Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();


This is working for me to get bluetooth information from an Arduino! :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download