首页 > 解决方案 > 在Android中通过蓝牙发送字符串

问题描述

我正在寻找如何在 Android 中通过蓝牙发送文本/字符串。我找到了结果

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

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

任务 :

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

上面的源代码是不可能的。那么,如何以编程方式通过蓝牙接收和发送字符串?

标签: javaandroidbluetooth

解决方案


推荐阅读