Android 通过免提协议(protocol)连接到蓝牙

标签 android bluetooth

我想创建一个可以通过免提协议(protocol) (HFP) 连接到蓝牙耳机的应用程序。我遵循了 Android 示例,现在有了一个带有 Input 和 OutputStreamBluetoothSocket。下面是我的读写方法(读方法由另一个Thread执行)

public void read() {
    while (true) {
        Log.d("ME", "Waiting for data");
        try { // read until Exception is thrown
            numBytes = inStream.read(dataBuffer);

            String str = new String(dataBuffer,0,numBytes);
            msgHandler.obtainMessage(numBytes, str).sendToTarget();
        } catch (Exception e) {
            Log.d("ME", "Input stream was disconnected", e);
            break; // BluetoothDevice was disconnected => Exit
        }
   }
}

public void write(byte[] bytes) {
    try {
        outStream.write(bytes);
        outStream.flush();
        Log.e("ME", "Wrote: " + new String(bytes));
    } catch (IOException e) {
        Log.e("ME", "Error occurred when sending data", e);
    }
}

当连接打开时,蓝牙耳机通过 InputStream 发送 AT+BRSF=191。我尝试使用 +BRSF:20\r 进行响应,但这是我的问题。之后,设备不会通过 InputStream 发送任何其他数据。它不会出现 Exception - 它更像是设备不知道如何响应我的消息。我发送了错误的数据吗?我有来自 here 的所有信息: (HF = 免提装置 AG = 音频网关)

enter image description here

你知道我做错了什么吗?我错过了什么吗?

编辑:这些是我的写调用:

write("+BRSF: 191\r");
write("OK\r");

最佳答案

您缺少 OK 响应。根据this documentOK-code 由一个 Windows 风格的换行符 (CR LF)、文字 OK 和另一个换行符组成。

请注意,其他命令仅由回车符终止。更多免提协议(protocol)可以引用that very document you linked in your post .

示例代码:

public static final String OK = statusCode("OK")
public static final String ERROR = statusCode("ERROR")

public static String statusCode(String code) {
    return "\r\n" + code + "\r\n";
}

public static String command(String cmd) {
    return cmd + "\r";
}

现在您可以在代码中使用OKERROR 作为常量,您可以使用statusCode 方法获取其他状态代码。

关于Android 通过免提协议(protocol)连接到蓝牙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41364403/

相关文章:

android - 在 Android 的 ViewPager 中禁用和启用分页

android - 为什么计数器变量的值在屏幕上没有变化?

ios - Bluetooth Low Energy 应用程序无法在 iOS 7 上写入特性

bluetooth - 将音频发送到支持蓝牙的扬声器,IOS

ios - 外设写入值: forCharacteristic: type: return null error and value

ios - 设备如何在CoreBluetooth中配对?

android - 在 Android 中从一项 Activity 转移到另一项 Activity

java - 如何从 OpenWeatherMap 获取图标

安卓蓝牙setpin功能

bluetooth - BLE 上的制造商特定数据