Reading data from paired Bluetooth devices in Android

I am working on an android 4.0 application that reads data from a paired Bluetooth device. I can search for a detected Bluetooth device and pair the devices. However, I'm not sure how to read data from a Bluetooth device via a serial port? Does the Android support system support SERIAL PORT? Because I can not find the serial port as COM1 or COM2 in the Android system. I am currently using BluetoothSocket to connect the device. However, is there a way to read data from a Bluetooth serial port, like Windows does?

socket = _devices.get(k).createRfcommSocketToServiceRecord(MY_UUID_SECURE); socket.connect(); 

Any help appreciated! Thanks in greeting.

Hi,

Charles

+4
source share
1 answer

Yes there is. The resulting socket can provide you with an instance of InputStream . If a socket connected, you can read data ( char , String or byte , depending on which reader you wrap around your InputStream , if you wrap it).

To open the serial port with the device, you must use the serial port profile in the UUID that you use to create your socket. Simple UUID thrown on the Internet,

 00001101-0000-1000-8000-00805F9B34FB 

Then you can create your socket, connect to it, receive streams and read / write bytes with them. Example:

 private static final String UUID_SERIAL_PORT_PROFILE = "00001101-0000-1000-8000-00805F9B34FB"; private BluetoothSocket mSocket = null; private BufferedReader mBufferedReader = null; private void openDeviceConnection(BluetoothDevice aDevice) throws IOException { InputStream aStream = null; InputStreamReader aReader = null; try { mSocket = aDevice .createRfcommSocketToServiceRecord( getSerialPortUUID() ); mSocket.connect(); aStream = mSocket.getInputStream(); aReader = new InputStreamReader( aStream ); mBufferedReader = new BufferedReader( aReader ); } catch ( IOException e ) { Log.e( TAG, "Could not connect to device", e ); close( mBufferedReader ); close( aReader ); close( aStream ); close( mSocket ); throw e; } } private void close(Closeable aConnectedObject) { if ( aConnectedObject == null ) return; try { aConnectedObject.close(); } catch ( IOException e ) { } aConnectedObject = null; } private UUID getSerialPortUUID() { return UUID.fromString( UUID_SERIAL_PORT_PROFILE ); } 

And then, somewhere in the code, you can read from the reader:

 String aString = mBufferedReader.readLine(); 

And you can do the same in the opposite direction using OutputStream and various authors.

+8
source

All Articles