Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class CommunicationExample extends Thread {
- private static final UUID UUID_PROBE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
- private static final String TAG = CommunicationExample.class.getSimpleName();
- private CommunicationExample.CommunicationListener mListener;
- private boolean mRunning;
- private BluetoothSocket mBluetoothSocket;
- private InputStream mInputStream;
- private OutputStream mOutputStream;
- public interface CommunicationListener {
- void onMessageReceived(String msg);
- }
- public CommunicationExample(
- @NonNull BluetoothDevice device,
- @Nullable CommunicationExample.CommunicationListener listener) throws IOException {
- // Faz a conexão utilizando o mesmo UUID que o servidor utilizou, no caso, o aferidor
- final BluetoothSocket socket = device.createRfcommSocketToServiceRecord(UUID_PROBE);
- socket.connect();
- this.mBluetoothSocket = socket;
- this.mInputStream = socket.getInputStream();
- this.mOutputStream = socket.getOutputStream();
- this.mListener = listener;
- }
- @Override
- public void run() {
- mRunning = true;
- // Faz a leitura
- final byte[] bytes = new byte[1024];
- int length;
- // Fica em loop para receber as mensagens
- while (mRunning) {
- try {
- Log.d(TAG, "Aguardando mensagem");
- // Lê a mensagem (fica bloqueado até receber)
- length = mInputStream.read(bytes);
- final String msg = new String(bytes, 0, length);
- Log.d(TAG, "Mensagem: " + msg);
- // Recebeu a mensagem (informa o listener)
- if (mListener != null)
- mListener.onMessageReceived(msg);
- } catch (Exception e) {
- Log.e(TAG, "Error na leitura da mensagem", e);
- }
- }
- }
- public void stopCommunication() {
- mRunning = false;
- mListener = null;
- try {
- if (mBluetoothSocket != null) {
- mBluetoothSocket.close();
- }
- if (mInputStream != null) {
- mInputStream.close();
- }
- if (mOutputStream != null) {
- mOutputStream.close();
- }
- } catch (IOException e) {
- Log.e(TAG, "Erro", e);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement