pro*_*pis 15 java android bluetooth
我正在使用蓝牙聊天来连接和接收来自蓝牙设备的数据.
我使用以下代码来读取数据:
public void run() {
byte[] buffer = new byte[1024];
int bytes;
Log.v("MR", "start listening....");
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
Log.d("MR", "buffer in try");
bytes = mmInStream.read(buffer);
Log.d("MR", "input stream :"+(new String(buffer)));
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(Conn.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
Log.d("MR", "buffer after");
} catch (Exception e) {
Log.e("MR", "Error :"+e.getMessage());
//
connectionLost();
// break;
}
Log.d("MR", "buffer after while");
}
}
Run Code Online (Sandbox Code Playgroud)
设备始终在不停止的情况下发送数据.
使用上面的代码我得到的信息是:
Log.d("MR", "buffer in try");
Run Code Online (Sandbox Code Playgroud)
然后它进入下一行:
bytes=mmInStream.read(buffer);
Run Code Online (Sandbox Code Playgroud)
并且永远不会从那个电话回来.我想这是因为它开始从设备读取数据,并且在断开连接之前不会停止.我怎样才能一次读取一定数量的字节?
编辑
除非它bytes = mmInStream.read(buffer);
因代码而停留在代码中; 否则从设备上获取任何数据?
JPM*_*JPM 14
我使用DataInputStreams,因为你可以做一个readFully()方法,它等待在返回之前读取一定数量的字节.我像这样设置BT连接:
BluetoothDevice btDevice = bta.getRemoteDevice(macAddress);
BluetoothSocket btSocket = InsecureBluetooth.createRfcommSocketToServiceRecord(
btDevice, UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), false);
btSocket.connect();
InputStream input = btSocket.getInputStream();
DataInputStream dinput = new DataInputStream(input);
Run Code Online (Sandbox Code Playgroud)
后来当我想阅读时我使用readFully:
dinput.readFully(byteArray, 0, byteArray.length);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
30571 次 |
最近记录: |