蓝牙代码在Android中发送字符串

时间:2017-04-05 05:25:17

标签: android bluetooth

我已经获得了蓝牙配对设备列表。现在我想将文本发送到该特定的配对设备。我已经为此完成了代码。

以下是代码:

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

但我得到了这些错误:

 java.io.IOException: read failed, socket might closed or timeout, read      ret: -1
 04-05 10:53:41.356 5580-5580/? W/System.err:     at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:900)
 04-05 10:53:41.356 5580-5580/? W/System.err:     at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:912)
 04-05 10:53:41.356 5580-5580/? W/System.err:     at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:531)

所以,请帮我解决这个错误。

1 个答案:

答案 0 :(得分:0)

您尝试连接哪种设备?

- &GT;基于讨论:如果尝试连接到运行Android的另一部手机,必须有接受连接的应用程序。 Google提供了工作示例:BluetoothChat

您可以尝试加快连接过程:

// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();

或者您可以尝试使用不同的UUID(是否有更多支持)?

System.out.println(uuids);

或者您可以尝试使用不安全的连接:

device.createInsecureRfcommSocketToServiceRecord(...)
BTW:您从inpust流中读取数据的代码无法正常工作。请查看Google聊天应用程序中的示例:BluetoothChatService