16
votes

I am using bluetooth chat in order to connect and recieve data from a bluetooth device.

I use the following code for reading data:

public void run() {
    byte[] buffer = new byte[1024];
    int bytes;
    Log.v("MR", "start listening....");

    // Keep listening to the InputStream while connected
    while (true) {
        try {
            // Read from the InputStream
            Log.d("MR", "buffer in try");

            bytes = mmInStream.read(buffer);
            Log.d("MR", "input stream :"+(new String(buffer)));
            // Send the obtained bytes to the UI Activity
            mHandler.obtainMessage(Conn.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
            Log.d("MR", "buffer after");

        } catch (Exception e) {
            Log.e("MR", "Error :"+e.getMessage());
            //
            connectionLost();
           // break;
        }

        Log.d("MR", "buffer after while");
    }
}

The device is sending data all the time without stopping.

With the above code I get the message of:

Log.d("MR", "buffer in try");

then it goes to the next line:

bytes=mmInStream.read(buffer);

and never returns from that call. I guess this is because it starts reading data from the device and doesn't stop until it disconnects. How can I read a certain amount of bytes at a time?

EDIT

Unless it stay to the bytes = mmInStream.read(buffer); code due to that it don;t get any data back on from the device?

1
th problem might not be the certain that i havce write on the top. i think it must be the port that it's make the communication. is it possible for the two devices to be connected but on the socket nothing to be transmitted os there is something that going wrong with the communication?prokopis
Upvotes would be nice lol...hope you are having some successJPM
having exactly same problemShirish Herwade

1 Answers

15
votes

I use DataInputStreams instead as you can do a readFully() method which waits to read a certain number of bytes before returning. I setup the BT connection like this:

BluetoothDevice btDevice = bta.getRemoteDevice(macAddress);
BluetoothSocket btSocket = InsecureBluetooth.createRfcommSocketToServiceRecord(
                    btDevice, UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), false);

btSocket.connect();
InputStream input = btSocket.getInputStream();
DataInputStream dinput = new DataInputStream(input);

then later on when I want to read I use readFully:

dinput.readFully(byteArray, 0, byteArray.length);