我已经在网上找到的教程的帮助下编写了一个连接到蓝牙设备的 Android 应用程序。这个应用程序使用 InputStream 和 OutputStream 对象来连接和建立连接。因为我必须传输少量数据,所以这个解决方案没问题,因为我只能发送字节。
现在我想更改我的旧代码以使用 DataInputStream 和 DataOutputStream 轻松发送复杂数据。我试图通过简单地在 InputStream 和 OutputStream 之前添加 Data 标识符来修改我的原始代码,但这在我的代码中产生了错误。有人可以解释一下如何正确使用 DataInputStream 和 DataOutputStream,这样我就不会出错。这是我的旧代码:
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
hBluetooth.obtainMessage(RECEIVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void send(String message) {
if(D) Log.d(TAG, "...Data to send: " + message + "...");
if (btSocket != null && btSocket.isConnected()) {
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
Log.e(TAG, "Int" +msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
这里是修改后的版本:
private class ConnectedThread extends Thread {
DataInputStream mmInStream;
DataOutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
mmInStream = new DataInputStream(tmpIn);
mmOutStream = new DataOutputStream(tmpOut);
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
感谢您的任何投入!