Send string via bluetooth on Android

Asked

Viewed 985 times

2

I’m developing an Android app that sends a string with the value ola by bluetooth.

How do I send ola by bluetooth to a specific address such as 00:00:00:00:00:00?

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

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.