Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading data from bluetooth device in android

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?

like image 628
prokopis Avatar asked Dec 07 '11 01:12

prokopis


People also ask

How get data from Bluetooth in Android programmatically?

Using the BluetoothSocket , the general procedure to transfer data is as follows: Get the InputStream and OutputStream that handle transmissions through the socket using getInputStream() and getOutputStream() , respectively. Read and write data to the streams using read(byte[]) and write(byte[]) .


1 Answers

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);
like image 184
JPM Avatar answered Oct 21 '22 07:10

JPM