在Android中通过蓝牙发送字符串

时间:2021-06-22 15:12:24

标签: java android bluetooth

我正在寻找如何在 Android 中通过蓝牙发送文本/字符串。我找到了 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();
        }
    }
}

我从代码中了解到,每次我通过蓝牙发送数据时,我都必须点击允许。但是,我想在我的应用程序中显示该字符串。

任务:

<块引用>

我将通过蓝牙从我的应用程序发送一个字符串,然后我将在另一部手机中获取并显示/使用该字符串。

以上源代码无法做到这一点。那么,如何以编程方式通过蓝牙接收和发送字符串?

0 个答案:

没有答案