Таким образом, я не знаю, как реализовать этот код для получения данных из соединения Bluetooth в Android Studio.
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
Этот код взят из этого метода, который является примером API-интерфейса Android для администрирования соединения
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);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
А это мой класс
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Handler;
public class AdministradorConexion extends Thread{
InputStream mmInStream;
OutputStream mmOutStream;
int handlerState = 0;
Handler bluetoothIn;
Context c;
//creation of the connect thread
public AdministradorConexion(BluetoothSocket socket,Context context) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
c = context;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(c, "La Conexión fallo", Toast.LENGTH_LONG).show();
Log.e("Error",e.getMessage());
// finish();
}
}
}
Я уже установил соединение и могу отправить данные
Похоже, ваш пост в основном кодовый; пожалуйста, добавьте еще некоторые детали.
И как я могу избежать повторения этой ошибки?