Juliano Silveira
Juliano Silveira

Reputation: 11

How to make Android App connect with multiple bluetooth devices?

I need my Android app to connect with multiple devices and exchange information with them.

To achieve this I am trying to create a thread that receives a connection from a device, save its MAC number, disconnect and open the connection to receive a new dispositive, but in all my attempts I can not restore the connection generating the Failed, because line management is giving an error.

Also, when the Bluetooth generates some error I can't create a method to retrieve a connection or to start a new one, I have to reboot the Bluetooth manually to re-establish a connection. And for my Android application, using the manual method to connect is not good.

Could someone help me show a way to manage the threads so I can connect and disconnect with multiple devices?

Below follows the code of the threads

private class ServeClass extends Thread {
    private BluetoothServerSocket serverSocket;

    public ServeClass() {
        try {
            //Servidor que recebe um Socket

            Log.e("BluetoothServerSocket","ServerSocket conectado");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void run() {


        while (socket == null) {
            try {
                Message message = Message.obtain();
                message.what = STATE_CONNECTING;
                // recebe um BluetoothSocket para gerenciar a mensagem
                socket = serverSocket.accept();

                handler.sendMessage(message);


            } catch (IOException e) {
                e.printStackTrace();
                Message message = Message.obtain();
                message.what = STATE_CONNECTION_FAILED;
                handler.sendMessage(message);
            }

            if (socket != null) {
                Message message = Message.obtain();
                message.what = STATE_CONNECTED;
                handler.sendMessage(message);

                sendRecive=new SendRecive(socket);
                sendRecive.start();

                break;
            }


        }

    }



}

Handler

Handler handler = new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case STATE_LISTENING:
                content.setText("Escutando");
                break;
            case STATE_CONNECTING:
                content.setText("Conectando");
                break;
            case STATE_CONNECTED:
                content.setText("Conectado");
                //botao.setVisibility(View.VISIBLE);
                break;
            case STATE_CONNECTION_FAILED:
                content.setText("Conexão Falha");
                break;
            case STATE_MESSAGE_RECEIVED:

                byte[] readBuffer= (byte[]) msg.obj;
                String tempMsg= new String(readBuffer,0,msg.arg1);
                botao.setText(tempMsg);


                break;

        }
        return true;
    }
});

Thread Send/Recive

private class SendRecive extends Thread {
    private final BluetoothSocket bluetoothSocket;
    private final InputStream inputStream;
    private final OutputStream outputStream;

    public SendRecive(BluetoothSocket socket) {
        bluetoothSocket = socket;
        InputStream tempIn = null;
        OutputStream tempOut = null;
        try {
            tempIn = bluetoothSocket.getInputStream();
            tempOut = bluetoothSocket.getOutputStream();
            Log.e("TESTE_CONTRUTOR", "TESTE_CONTRUTOR");

        } catch (IOException e) {
            e.printStackTrace();
        }

        inputStream = tempIn;
        outputStream = tempOut;

    }

    @Override
    public void run() {
        byte[] buffer = new byte[1024];
        int bytes;

        while (true) {
            try {
                bytes = inputStream.read(buffer);
                handler.obtainMessage(STATE_MESSAGE_RECEIVED, bytes, -1, buffer).sendToTarget();

                socket = null;

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void write(byte[] bytes) {
        try {
            outputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Thread Client

    private class ClientClass extends Thread {
    private BluetoothSocket socket;
    private BluetoothDevice device;

    public ClientClass(BluetoothDevice device) {
        this.device = device;

        try {
            socket = this.device.createRfcommSocketToServiceRecord(MYUUID);
        } catch (Exception e) {
            Log.e("Erro", String.valueOf(e));
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            socket.connect();
            Message message = Message.obtain();
            message.what = STATE_CONNECTED;
            handler.sendMessage(message);

            sendRecive = new SendRecive(socket);
            sendRecive.start();
        } catch (IOException e) {
            e.printStackTrace();
            Message message = Message.obtain();
            message.what = STATE_CONNECTION_FAILED;
            handler.sendMessage(message);
        }
    }

    public void cancel() {

        try {

            socket.close();
            Message message = Message.obtain();
            message.what = STATE_LISTENING;
            handler.sendMessage(message);



        } catch (IOException e) {
            e.printStackTrace();
        }

    }

Upvotes: 1

Views: 3181

Answers (2)

ZOF MOD
ZOF MOD

Reputation: 1

Classic Bluetoith impossible to connect with more than one device at the same time as the protocol of BL-Classic is pair to pair. That is not correct here's proof. https://youtu.be/iMEm3QrP37Q

Upvotes: 0

Waged
Waged

Reputation: 420

let me ask a question do you have bluetooth classic or bluetooth low energy ? If bluetooth Classic then It's impossible to connect with more than one device at the same time as the protocol of BL-Classic is pair to pair connection. in case of using Bluetooth Low Energy then it's doable and I have made a code for single device but you can manipulate the code by doing different services with different UUIDs and it should work. Here's the Link : https://github.com/Waged/BLEArduino

Upvotes: 0

Related Questions