Android Bluetooth LE API edit

Connect to Bluetooth device

After you obtained BluetoothDevice, you can communicate with it. This kind of communication performed by using socket input\output streams:

Those are the basic steps for Bluetooth communication establishment:

1) Initialize socket:

private BluetoothSocket _socket;
//...
public InitializeSocket(BluetoothDevice device){
   try {
       _socket = device.createRfcommSocketToServiceRecord(<Your app UDID>);
   } catch (IOException e) {
       //Error
   }
 }

2) Connect to socket:

try {
    _socket.connect();
} catch (IOException connEx) {
    try {
        _socket.close();
    } catch (IOException closeException) {
        //Error
    }
}

if (_socket != null && _socket.isConnected()) {
    //Socket is connected, now we can obtain our IO streams
}

3) Obtaining socket Input\Output streams

private InputStream _inStream;
private OutputStream _outStream;
//....
try {
    _inStream = _socket.getInputStream();
    _outStream =  _socket.getOutputStream();
} catch (IOException e) {
   //Error
}

Input stream - Used as incoming data channel (receive data from connected device)

Output stream - Used as outgoing data channel (send data to connected device)

After finishing 3rd step, we can receive and send data between both devices using previously initialized streams:

1) Receiving data (reading from socket input stream)

byte[] buffer = new byte[1024];  // buffer (our data)
int bytesCount; // amount of read bytes

while (true) {
    try {
        //reading data from input stream
        bytesCount = _inStream.read(buffer);
        if(buffer != null && bytesCount > 0)
        {
            //Parse received bytes
        }
    } catch (IOException e) {
        //Error
    }
}

2) Sending data (Writing to output stream)

public void write(byte[] bytes) {
    try {
        _outStream.write(bytes);
    } catch (IOException e) {
        //Error
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Table Of Contents
39 ACRA
64 Menu
67 Bluetooth LE API
112 Loader
119 Xposed
132 Colors
135 Fresco
140 AdMob
147 Button
156 Vk SDK
170 XMPP
176 OpenCV
200 FileIO
203 Moshi
217 Paint
231 AIDL
241 JCodec
243 Okio
255 Looper
  ↑ ↓ to navigate     ↵ to select     Esc to close