在网上找到的教程的帮助下,我已经编写了一个连接到蓝牙设备的Android应用程序。这个应用程序使用InputStream和OutputStream对象来连接和建立连接。因为我必须传输少量数据,所以这个解决方案是可以的,因为我只能发送字节。
现在我想改变我的旧代码使用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;
}
谢谢你的建议!
如果我正确理解了你的问题,那么做这样的事情来获得DataInputStream和DataOutputStream对象:
mmInStream = new DataInputStream(tmpIn);
mmOutStream = new DataInputStream(tmpOut);
如果你需要它们是全局的,那么变量将像下面这样在类外声明:
DataInputStream mmInStream;
DataOutputStream 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 = new DataInputStream(tmpIn);
mmOutStream = new DataOutputStream(tmpOut);
}