akexorcist / BluetoothSPPLibrary

[UNMAINTAINED][Android] Bluetooth Serial Port Profile which comfortable to developer application to communication with microcontroller via bluetooth
Apache License 2.0
1.71k stars 571 forks source link

Fixing send function #95

Closed murwa closed 5 years ago

murwa commented 6 years ago

Hello, so I wanted to send some commands to a bluetooth scale, and this library was doing everything but that. After a couple of days (more like weeks actually), I came up with a solution. Basically extend BluetoothSPP class. So for all of us having issues (#80 and #56 ) with send function, here's my solution.

public class BluetoothSPP extends app.akexorcist.bluetotohspp.library.BluetoothSPP {
    private static final String TAG = BluetoothSPP.class.getSimpleName();

    public BluetoothSPP(Context context) {
        super(context);
    }

    @Override
    public void send(byte[] data, boolean CRLF) {
        Set<BluetoothDevice> bonded = this.getBluetoothAdapter().getBondedDevices();
        if (bonded.size() > 0) {
            BluetoothDevice device = (BluetoothDevice) bonded.toArray()[0];
            ParcelUuid[] uuids = device.getUuids();
            BluetoothSocket socket = null;
            try {
                socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                OutputStream out = socket.getOutputStream();
                Log.d(TAG, "Sending byte data to bluetooth...");
                out.write(data);
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        Log.e(TAG, e.getMessage());
                    }
                }
            }
        }
    }

    @Override
    public void send(String data, boolean CRLF) {
        this.send(data.getBytes(), CRLF);
    }

    public void send(String data) {
        this.send(data.getBytes(), true);
    }

    public void send(byte[] data) {
        this.send(data, true);
    }
}
murwa commented 5 years ago

My bad. Actually the send functionality was working just fine. The issues was that I was terminating the service from time to time. That should not be the case.