[英]Android Bluetooth socket connection receiving data in background with AsyncTask
[英]Trouble receiving data from Android Bluetooth connection
我有一個連接到藍牙伴侶銀芯片的android應用程序。 我正在測試它的發送/接收功能。 通常,我一直在android dev網站上關注藍牙示例。
我可以說發送數據是可行的,因為當我向芯片寫入(“ $$$”)時,它將進入命令模式並非常快速地閃爍其狀態LED。 當芯片進入命令模式時,它將發送答復:“ CMD”。 我在收到此回復時遇到問題。
當我按下一個按鈕時,將執行以下代碼。 mct是我用來讀寫的全局ConnectedThread。 盡管形式很差,但是所有函數都在MainActivity.java內部
if(connected){
if (cmdMode == false){
mct.write("$$$".getBytes()); //enter command mode
mct.listen();
TextView lbl_history = (TextView) findViewById(R.id.lbl_history);
lbl_history.setText(message);
cmdMode = true;
}
else{
mct.write("k,\n".getBytes()); //kill the connection
cmdMode = false;
}
}
我的交流線程:
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void listen() {
handled = false;
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
reply=null;
while (reply==null) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
reply = buffer.toString();
//message is a global String to store the latest message received
message = reply;
} catch (IOException e) {
break;
}
}
reply = null;
}
//write and cancel functions removed for simplicity
}
當我運行此代碼時,結果是一個文本視圖,顯示“ [B @ 415f8910””,我認為這是垃圾。 同一代碼的多次運行將產生相似的結果,但最后幾位數字會有所不同。 預期結果將為“ CMD”。 對這里的問題有什么想法嗎? 我是android開發的新手,因此不勝感激。
進一步檢查發現,多次運行嚴格增加了“ [B @ 415f8910””,使我相信它是一個內存地址。 不過,我仍然不知道該怎么辦。
我發現了問題。 我不需要直接在字節數組上調用“ toString()”,而是需要調用String構造函數來正確轉換數據:
String message = new String(buffer, "UTF-8");
指定UTF-8是什么與眾不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.