2012-12-13 103 views
0

我正面臨以下問題: 我通過藍牙接口,一個平板android和一個藍牙設備(如閱讀器條形碼)連接兩個設備,直到現在沒問題,問題是,當通過藍牙設備讀取條形碼並將其發送到平板電腦時,條形碼有時以兩部分發送,例如,如果我讀取內容爲「212154521212」的條形碼,則該平板電腦收到「2121」,在「 54521212「,任何人都知道告訴我該怎麼做才能避免這種情況?通過藍牙設備發送數據到平板電腦的錯誤

謝謝先進。

我的代碼從藍牙設備中讀取的數據:

[代碼] 私有類ConnectedThread擴展Thread {

private final InputStream mmInStream; 
    private BluetoothSocket socket; 

    public ConnectedThread(BluetoothSocket socket) { 
     this.socket = socket; 

     InputStream tmpIn = null; 

     try { 

      tmpIn = socket.getInputStream(); 

     } catch (IOException e) { 
      new LogDeErrosRodesTablet(e); 
      Log.e(TAG, e.getMessage()); 
      Log.e(TAG, "Erro no construtor da classe ConnectedThread."); 

     } 

     mmInStream = tmpIn; 
    } 

    public void run() {  
     // continua lendo o inputstream até ocorrer um erro 

     while (true) { 

      int read = 0; 
      byte[] buffer = new byte[128]; 

      do { 

       try { 

        read = mmInStream.read(buffer); 
        Log.e(TAG, "read: " + read); 
        final String data = new String(buffer, 0, read); 
        Log.e(TAG, "data: " + data); 

        //TODO 
        //send data only (bar code) only after read all 
        Bundle bundle = new Bundle(); 
        bundle.putString(TelaInserirPedido.CODIGO_BARRAS, data); 
        Message message = new Message(); 
        message.what = TelaInserirPedido.MSG_COD_BARRAS; 
        message.setData(bundle); 

        //Send a message with data 
        handler.sendMessage(message); 

       } catch(Exception ex) { 
        read = -1; 
        return; 
       } 

       Log.e(TAG, "inside while."); 

      } while (read > 0); 

      Log.e(TAG, "outside of while."); 
     } 

    } 

    public void cancel() { 
     try { 
      socket.close(); 
     } catch (IOException e) { } 
    } 

} 

[/代碼]

回答

0

使用OutputStream.flush()來強制發送所有數據。

+0

什麼是OutputStream? –

+0

您用來發送條形碼的OutputStream。 – user1888162

+0

在任何時候我都使用過OutPutStream。 –

1

這不是藍牙錯誤。藍牙設備正在將所有數據發送到您的應用程序,但您在收到所有數據之前正在讀取數據流。如果您知道數據的確切長度,則可以在讀取之前檢查流上可用的字節數();您可以連接所有讀取的結果,直到達到已知的終點。或者你可以放任意的時間延遲,並希望在那個時候完成傳輸。

您將在收集輸入字符串的while循環之後創建Bundle和Message,因爲在該循環結束之前您不知道整個字符串。 (除非您希望在一個連接中使用多個字符串,在這種情況下,您需要更復雜的代碼來處理部分數字)。

相關問題