0

I was searching how to send text/String via Bluetooth in Android. I found the result.

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) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

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();
        }
    }
}

What I understand from the code that is, I have to click on allow everytimes I send data via Bluetooth. But, I want to show that String in my application.

Task :

I will send a String via Bluetooth from my application then, I will take and show/work with that String in another mobile.

Which isn't possible by above source code. So, how can I receive and send String via Bluetooth programmatically?

Anonymous
  • 13
  • 5
  • You're setup to receive the `byte` data in your `run()` method. Just [convert it to a String](https://stackoverflow.com/questions/1536054/how-to-convert-byte-array-to-string-and-vice-versa) and send it where you need it. – Tim Hunter Jun 22 '21 at 15:24

0 Answers0