Send string via bluetooth on Android

2

I'm developing an Android app that sends a string with ola value over bluetooth.

How do I send ola through bluetooth to a specific address like 00:00:00:00:00:00 ?

A function that sends a string through bluetooth to a specific address would be a great help.

    
asked by anonymous 15.05.2015 / 13:43

1 answer

2

Hello, good friend!

Try this:

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0){
                BluetoothDevice[] devices = (BluetoothDevice[]) bondedDevices.toArray();
                BluetoothDevice device = devices[0];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("erro", "Dispositivos não estão conectados.");
        }else{
            Log.e("error", "Bluetooth está desligado.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The source of this code is here .

    
17.05.2015 / 01:08