Я уже писал с помощью учебников я нашел в Интернете приложение для Android, которое подключается к устройству Bluetooth. Это приложение использовало объекты InputStream и OutputStream для подключения и установления соединения. Поскольку мне нужно было передать небольшой объем данных, это решение было в порядке, потому что я мог отправлять только байты.
Теперь я хотел бы изменить свой старый код, чтобы использовать DataInputStream и DataOutputStream для простой отправки сложных данных. Я попытался изменить свой исходный код, просто добавив идентификатор данных перед моими 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;
}
Спасибо за любой вклад!