I already wrote with the help of tutorials I found on the Internet a app for Android that connect to a Bluetooth device. This app used the InputStream and OutputStream object to connect and establish a connection. Because I had to transfer small amount of data this solution was OK because I could only send bytes.
Now I would like to change my old code to use DataInputStream and DataOutputStream to send complex data easily. I tried to modify my original code by simply adding the Data identifier before my InputStream and OutputStream but this created error in my code. Could someone explain me how to use the DataInputStream and DataOutputStream correctly so I will not get errors. This is my old code :
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() + "...");
}
}
}
and here the modified version :
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;
}
Thanks for any inputs!