Error to send data to tablet through bluetooth device
我面临以下问题:
我正在通过蓝牙outlets连接两个设备,一个平板电脑android和一个蓝牙设备(如阅读器条形码),到目前为止还可以,问题是,当通过蓝牙设备读取条形码并将其发送到平板电脑时,条形码有时会分为两部分发送,例如,如果我读到内容为" 212154521212"的条形码,则平板电脑会收到" 2121",而在" 54521212"之后,有人知道告诉我该怎么做我要避免这种情况吗?
非常感谢。
从蓝牙设备读取数据的代码:
[代码]
私有类ConnectedThread扩展了线程{
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 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) { } } } |
[/ code]
这不是蓝牙错误。蓝牙设备正在将所有数据发送到您的应用程序,但是您在接收所有数据之前正在读取流。如果您知道数据的确切长度,则可以在读取之前检查流中的available()字节数。您可以将所有读取的结果连接起来,直到达到已知的终点。或者,您可以设置任意时间延迟,并希望在该时间内完成传输。
您将在收集输入字符串的while循环之后创建Bundle和Message,因为直到该循环结束,您才知道整个字符串。 (除非您期望在一个连接中有多个字符串,否则在这种情况下,您需要更复杂的代码来处理部分数字)。
使用OutputStream.flush()强制发送所有数据。