Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...