Read Data From Paired Bluetooth Devices In Android
I am working on an android 4.0 application which reads data from the paired bluetooth device. I am able to search discoverable bluetooth device and pair the devices. However, I am
Solution 1:
Yes there is. The socket
you receive can give you an InputStream
instance. If the socket
is connected, you can then read data (char
, String
or byte
, depending on what reader you will wrap around your InputStream
, if you wrap one).
To open a serial port with the device, you have to use the Serial Port Profile in the UUID you use to create your socket. A simple UUID thrown around on the web is
00001101-0000-1000-8000-00805F9B34FB
You can then create your socket, connect to it, get streams and read/write bytes with them. Example :
privatestaticfinalStringUUID_SERIAL_PORT_PROFILE="00001101-0000-1000-8000-00805F9B34FB";
privateBluetoothSocketmSocket=null;
privateBufferedReadermBufferedReader=null;
privatevoidopenDeviceConnection(BluetoothDevice aDevice)throws IOException {
InputStreamaStream=null;
InputStreamReaderaReader=null;
try {
mSocket = aDevice
.createRfcommSocketToServiceRecord( getSerialPortUUID() );
mSocket.connect();
aStream = mSocket.getInputStream();
aReader = newInputStreamReader( aStream );
mBufferedReader = newBufferedReader( aReader );
} catch ( IOException e ) {
Log.e( TAG, "Could not connect to device", e );
close( mBufferedReader );
close( aReader );
close( aStream );
close( mSocket );
throw e;
}
}
privatevoidclose(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 your code you can read from the reader:
StringaString= mBufferedReader.readLine();
And you can do the same thing in opposite direction using OutputStream
and various writers.
Post a Comment for "Read Data From Paired Bluetooth Devices In Android"