2011-07-09 58 views
4

我使用的是android:BluetoothChat的示例應用程序。 但是,當我嘗試發送字符串,它的大小更大的1024字節消息不傳輸。 我嘗試改變下面的代碼發送更多然後1024字節,但我沒有在這個成功。 請幫幫我。在Android上通過藍牙發送長文本信息

讀碼:

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(SmallWorld.MESSAGE_READ, bytes, -1, 
          buffer).sendToTarget(); 

       } catch (IOException e) { 
        Log.e(TAG, "disconnected", e); 
        connectionLost(); 
        break; 
       } 
      } 
     } 

發送代碼:

public void write(byte[] buffer) { 
     try { 
      mmOutStream.write(buffer); 

      // Share the sent message back to the UI Activity 
      mHandler 
        .obtainMessage(SmallWorld.MESSAGE_WRITE, -1, -1, buffer) 
        .sendToTarget(); 
     } catch (IOException e) { 
      Log.e(TAG, "Exception during write", e); 
     } 
    } 

調用write:

String message="blabla"; 
byte[] send = message.getBytes(); 
     mChatService.write(send); 
+0

什麼是您得到的錯誤消息? –

+0

我沒有收到錯誤消息,它只發送1024字節的字符串(它切斷了字符串),即使我改變了緩衝區的大小。 – Beno

+0

其中是發送字符串的代碼 –

回答

2

寫之後,你可能要刷新流數據強制被髮送出去,因爲在實際發送數據之前,數據流可能會緩衝數據並等待更多數據。 試試..

mmOutStream.write(buffer); 
mmOutStream.flush(); 
+0

謝謝,我明天會檢查。 – Beno

+0

它的工作,但現在我有一個新問題。數組的最大大小是多少:new byte [1024]; 我得到內存泄漏 – Beno