看板 AndroidDev 關於我們 聯絡資訊
※ 引述《fake01 (code)》之銘言: : 使用手機藍芽接值,而接的值是由硬體端不斷丟值, : 通常一秒丟一串字串 例如 123$456# or 455$123$ : 但是藍芽這邊接一次有時候會漏掉值 123456# 或 123$56, : 但有時候又會正常接,是無法判斷硬體這邊丟一次的字串是甚麼, : 請問該如何解決呢 : case MESSAGE_READ: : byte[] readBuf = (byte[]) msg.obj; : // construct a string from the valid bytes in the buffer : String readMessage = null; : try { : readMessage = new String(readBuf, 0,msg.arg1,"GBK"); : } : catch (UnsupportedEncodingException e) : { : // TODO Auto-generated catch block : e.printStackTrace(); : } : break; : // 以上就是藍芽抓值的code,麻煩各位了 因為C大說貼socket部分的code 會比較好懂,我是用Chat? 那個藍芽範例所改的應該沒甚麼問題 private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) { Log.d(TAG, "create ConnectedThread"); mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Get the BluetoothSocket input and output streams try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { Log.e(TAG, "temp sockets not created", e); } mmInStream = tmpIn; mmOutStream = tmpOut; } public void run() { Log.i(TAG, "BEGIN mConnectedThread"); byte[] buffer = new byte[1024]; int bytes; // Keep listening to the InputStream while connected while (true) { try { // Read from the InputStream bytes = mmInStream.read(buffer); // Send the obtained bytes to the UI Activity mHandler.obtainMessage(TestbtActivity.MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); } catch (IOException e) { Log.e(TAG, "disconnected", e); connectionLost(); break; } } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.58.82.128
MetalChao:我不知道你掉值的問題在哪, 不過對於你的code有幾點想法 02/01 20:09
MetalChao:1. 你的值內容是什麼樣子? 為什麼要用 GBK encoding? 02/01 20:10
MetalChao:2. constructor 如果真的有 io exception, 你只是忽略掉 02/01 20:11
MetalChao:那麼接下來的 run 裡就會有 null pointer exception 02/01 20:12
MetalChao:3. tmpIn tmpOut 這兩個變數是不需要的 02/01 20:12
fake01:掉直就像是應該要給123#456 變成 #456 或 56 02/02 00:11
fake01:因為傳值端丟過來的值要用GBK才看得懂 02/02 00:11