2016-12-28 40 views
1

我想創建一個可以通過免提協議(HFP)連接到藍牙耳機的應用程序。我遵循Android示例,現在有BluetoothSocket及其Input and OutputStream。下面你看到我的讀取和寫入方法(讀法是由另一Thread執行)Android通過免提協議連接到藍牙

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=191InputStream。我試圖迴應+BRSF:20\r但這是我的問題。之後,設備不會通過InputStream發送任何其他數據。它不會來到Exception - 它更像是設備不知道如何回覆我的信息。我會發送錯誤的數據嗎?我從here的所有信息:(HF =免提單位AG =音頻網關)

enter image description here

你有任何想法,我做錯了什麼?我錯過了什麼嗎?

編輯:這是我寫電話:

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

這可能是一個愚蠢的評論,但你有沒有嘗試不同的行終止? – Distjubo

+0

我用'\ r','\ n'和'\ r \ n'嘗試過。我應該嘗試其他嗎? – Cilenco

+0

nah。但是'+ BRSF ='下方有什麼'OK'消息?你不應該發送嗎? – Distjubo

回答

1

你失蹤了OK響應。根據this documentOK-code由一個窗口式換行符(CR LF),字面值OK和另一個換行符組成。

請注意,其他命令僅由回車終止。有關免提協議的更多信息,請參閱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方法。