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

时间:2016-12-28 14:50:20

标签: android bluetooth

我想创建一个可以通过免提协议(HFP)连接到蓝牙耳机的应用程序。我按照Android示例进行了操作,现在BluetoothSocket的{​​{1}}版本为Input and OutputStream。下面你看到我的读写方法(读取方法由另一个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);
    }
}

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

enter image description here

你有什么想法我做错了吗?我错过了什么吗?

编辑:这些是我的写电话:

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

1 个答案:

答案 0 :(得分:1)

您错过了OK回复。根据{{​​3}},OK - 代码由一个窗口式换行符(CR LF),文字OK和另一个换行符组成。

请注意,其他命令仅由回车符终止。有关免提协议的更多信息,请参阅this document

示例代码:

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方法用于其他状态代码。

相关问题